Description:
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
Analysis:
Use dp[i]
to denote the maximum sum of first i items of the array after partitioning.
d
p
[
i
]
=
m
a
x
{
d
p
[
i
−
1
]
+
A
[
i
−
1
]
∗
1
d
p
[
i
−
2
]
+
m
a
x
{
A
[
i
−
2
]
,
A
[
i
−
1
]
}
∗
2
d
p
[
i
−
3
]
+
m
a
x
{
[
A
[
i
−
3
]
,
A
[
i
−
2
]
,
A
[
i
−
1
]
}
∗
3
dp[i] = max \begin{cases} dp[i-1] + A[i-1] * 1 \\ dp[i-2] + max\{A[i-2], A[i-1]\} * 2 \\ dp[i-3] + max\{[A[i-3], A[i-2], A[i-1]\} * 3 \\ \end{cases}
dp[i]=max⎩⎪⎨⎪⎧dp[i−1]+A[i−1]∗1dp[i−2]+max{A[i−2],A[i−1]}∗2dp[i−3]+max{[A[i−3],A[i−2],A[i−1]}∗3
Code:
class Solution {
public int maxSumAfterPartitioning(int[] A, int K) {
int n = A.length;
int[] dp = new int[n+1];
for(int i = 1; i <= n; i++) {
int curMax = 0;
for(int j = 1; j <= K; j++) {
if((i-j)>=0){
curMax = Math.max(curMax, A[i-j]);
dp[i] = Math.max(dp[i], dp[i-j] + curMax*j);
}
}
}
return dp[n];
}
}