[LeetCode] Partition Array for Maximum Sum

1043. Partition Array for Maximum Sum

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
int dp[505];
int helper(vector<int>& A, int k, int p) {
if(p == A.size()) return 0;
if(dp[p] != -1) return dp[p];
int n = A.size();
for(int i = p, ma = 0; i < min(n, p + k); i++) {
ma = max(ma, A[i]);
dp[p] = max(dp[p], ma * (i - p + 1) + helper(A, k, i + 1));
}
return dp[p];
}
public:
int maxSumAfterPartitioning(vector<int>& A, int k) {
memset(dp, -1, sizeof dp);
return helper(A,k,0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/15/PS/LeetCode/partition-array-for-maximum-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.