Given an integer array A, you 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.

Example 1:

Input: A = [1,15,7,9,2,5,10], K = 3
Output: 84
Explanation: A becomes [15,15,15,9,10,10,10]

Note:

1. 1 <= K <= A.length <= 500
2. 0 <= A[i] <= 10^6

## Solution: DP

Time complexity: O(n*k)
Space complexity: O(n)

dp[i] := max sum of A ~ A[i]
init: dp = 0
transition: dp[i] = max{dp[i – k] + max(A[i-k:i]) * k}, 1 <= k <= min(i, K)
ans: dp[n]

A = | 2 | 1 | 4 | 3 |
K = 3
dp = 0
dp = max(dp + 2 * 1) = 2
dp = max(dp + 2 * 2, dp + 1 * 1) = max(4, 3) = 4
dp = max(dp + 4 * 3, dp + 4 * 2, dp + 4 * 1) = max(12, 10, 8) = 12
dp = max(dp + 4 * 3, dp + 4 * 2, dp + 3 * 1) = max(14, 12, 15) = 15
best = | 4 | 4 | 4 | 3 |


## C++

If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website ## Be First to Comment

Mission News Theme by Compete Themes.