Partition Array for Maximum Sum Problem
Description
LeetCode Problem 1043.
Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: arr = [1,15,7,9,2,5,10], k = 3
Output: 84
Explanation: arr becomes [15,15,15,9,10,10,10]
Example 2:
Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
Output: 83
Example 3:
Input: arr = [1], k = 1
Output: 1
Constraints:
1 <= arr.length <= 5000 <= arr[i] <= 10^91 <= k <= arr.length
Solution
Approach: Dynamic Programming on Prefixes
Let f[i] be the largest sum we can get from the first i elements. The last piece of the best partition of those i elements ends at arr[i-1] and has some length len from 1 to k. Everything before it is again a best partition of a shorter prefix, so
f[i] = max over len = 1..min(k, i) of f[i - len] + len * max(arr[i-len..i-1])
with f[0] = 0. The answer is f[n].
To get the piece's maximum without rescanning, grow the last piece to the left one element at a time and keep a running maximum: each new element either raises the maximum or leaves it unchanged.
The products can look large (arr[i] goes up to 109), but every candidate is the sum of a real partition of a prefix, and all values are non-negative, so no candidate exceeds the final answer, which fits in 32 bits.
Complexity: O(n * k) time and O(n) space.
class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
n = len(arr)
f = [0] * (n + 1) # f[i]: best sum for the first i elements
for i in range(1, n + 1):
best = 0 # largest value of the last piece arr[j-1..i-1]
# Try every length 1..k for the last piece, growing it to the left.
for j in range(i, max(0, i - k), -1):
best = max(best, arr[j - 1])
f[i] = max(f[i], f[j - 1] + best * (i - j + 1))
return f[n]