2-D Dynamic Programming Splitting a range
576. Partition Array for Maximum Sum
You are given an array of non-negative integers arr and an integer k. Split arr into blocks of
neighbouring elements. Every element goes into exactly one block, and each block holds from 1 to k
elements.
Then, inside each block, replace every element with the largest element of that block. Return the largest sum the array can have after this, over all the ways to split it.
The blocks keep the array's order: you choose only where one block ends and the next begins. When k is at
least the length of arr, the whole array may be one block.
Example 1
Input: arr = [2, 9, 3, 1, 8, 4, 6], k = 2
49Explanation: Split it into [2, 9], [3], [1, 8] and [4, 6]. The array becomes [9, 9, 3, 8, 8, 6, 6], and
18 + 3 + 16 + 12 = 49. Blocks of exactly two from the left, [2, 9], [3, 1], [8, 4] and [6],
give only 46.
Example 2
Input: arr = [3, 8, 1, 6], k = 6
32Explanation: k = 6 is more than the length, so the whole array can be one block. Every element becomes 8, and
4 × 8 = 32.
Example 3
Input: arr = [1000000000, 0, 0, 1000000000, 0], k = 2
4000000000Explanation: Split it into [1000000000, 0], [0, 1000000000] and [0]. Each pair becomes two copies of
109, so the sum is 4 × 109. The last 0 adds nothing.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ arr.length ≤ 1050 ≤ arr[i] ≤ 1091 ≤ k ≤ 100
Clarifying questions
What you would ask an interviewer before writing any code.