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 <= K <= A.length <= 500
0 <= A[i] <= 10^6
Related Topics:
Graph
Let dp[i]
be the subproblem in A[0..i]
.
dp[i] = max( dp[j-1] + max(A[j], ..., A[i]) * (i - j + 1) | i - j + 1 <= K && j >= 0 )
dp[-1] = 0
// OJ: https://leetcode.com/problems/partition-array-for-maximum-sum/
// Author: github.com/lzl124631x
// Time: O(NK)
// Space: O(N)
class Solution {
public:
int maxSumAfterPartitioning(vector<int>& A, int K) {
int N = A.size();
vector<int> dp(N);
for (int i = 0; i < N; ++i) {
int maxVal = 0;
for (int j = i, k = 0; j >= 0 && k < K; --j, ++k) {
maxVal = max(maxVal, A[j]);
dp[i] = max(dp[i], (j == 0 ? 0 : dp[j - 1]) + maxVal * (i - j + 1));
}
}
return dp[N - 1];
}
};
// OJ: https://leetcode.com/problems/partition-array-for-maximum-sum/
// Author: github.com/lzl124631x
// Time: O(NK)
// Space: O(K)
class Solution {
public:
int maxSumAfterPartitioning(vector<int>& A, int K) {
int N = A.size();
++K;
vector<int> dp(K);
for (int i = 0; i < N; ++i) {
int maxVal = 0;
dp[i % K] = 0;
for (int j = i, k = 0; j >= 0 && k < K - 1; --j, ++k) {
maxVal = max(maxVal, A[j]);
dp[i % K] = max(dp[i % K], (j == 0 ? 0 : dp[(j - 1) % K]) + maxVal * (i - j + 1));
}
}
return dp[(N - 1) % K];
}
};