# 1043. Partition Array for Maximum Sum

Given an integer array `arr`, you should 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: 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`

``````class Solution {
public:
int maxSumAfterPartitioning(vector<int>& arr, int k) {
int n = arr.size();
vector<int> dp(n + 1);
for (int i = 1; i <= n; ++i) {
int curMax = 0;
for (int j = 1; j <= k && i - j >= 0; ++j) {
curMax = max(curMax, arr[i - j]);
dp[i] = max(dp[i], dp[i - j] + curMax * j);
}
}
return dp[n];
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1043

https://leetcode.com/problems/partition-array-for-maximum-sum/

https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/291057/Java-visualize-the-pattern

https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/290863/JavaC%2B%2BPython-DP-O(K)-Space

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation