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 <= 500
0 <= arr[i] <= 109
1 <= k <= arr.length
This problem asks to partition an array into contiguous subarrays of length at most k, such that the sum of the maximum values in each subarray is maximized. This can be efficiently solved using dynamic programming.
The core idea is to build a dynamic programming solution where dp[i]
represents the maximum sum achievable after partitioning the array up to index i
. We iterate through the array, and for each index i
, we consider all possible subarray lengths up to k
ending at i
.
State Transition:
To calculate dp[i]
, we iterate through possible starting indices j
of the last subarray (from i - k
to i
). For each j
, we find the maximum value max_val
within the subarray [j, i]. The maximum sum achievable up to index i
is then given by:
dp[i] = max(dp[i], dp[j-1] + max_val * (i - j + 1))
This formula represents choosing the best partitioning where the last subarray starts at index j
and ends at index i
. We add the maximum sum achievable up to j-1
(dp[j-1]
) and the contribution of the last subarray (max_val * (i - j + 1)
).
Base Case:
dp[0] = 0
(no sum for an empty partition).
Final Result:
The final answer is dp[n]
, where n
is the length of the array.
dp
array of size n+1.def maxSumAfterPartitioning(arr, k):
n = len(arr)
dp = [0] * (n + 1) # Initialize dp array
for i in range(1, n + 1):
max_val = 0
for j in range(i, max(0, i - k), -1): # Iterate through possible subarray lengths
max_val = max(max_val, arr[j - 1]) # Find max value in current subarray
dp[i] = max(dp[i], dp[j - 1] + max_val * (i - j + 1)) # Update dp[i]
return dp[n]
The implementations in other languages (Java, C++, Go, TypeScript) follow a similar logic, only differing in syntax. They all maintain a DP array and iteratively compute the maximum sum based on the state transition equation described above.