题:https://leetcode.com/problems/partition-array-for-maximum-sum/
题目大意
对于一个数组A,将A分割为多个连续的子数组,每个子数组长度不能超过K。
将A中每个元素置换为 对应子数组中最大值 ,从而形成新数组,求新数组的和 最大能为多少。
思路
动态规划
int dp[i] :数组 A[0:i] 形成新数组的最大和。
初始化状态:
dp[0] = 0
状态转移方程:
int tMax = 0;
for(int j = i - 1; i - j <= K && j>=0;j--){
tMax = Math.max(tMax,A[j]);
dp[i] = Math.max(dp[i],dp[j] + tMax *(i-j));
}
dp[i] = Max( 从当前位置i 往前 取一个子数组A[j:i] ,将该子数组中的所有元素都 置换为 子数组中最大值后,求该子数组的和tMax *(i-j), tMax *(i-j) + dp[j]) ,其中 i - j<= K && j >= 0
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 tMax = 0;
for(int j = i - 1; i - j <= K && j>=0;j--){
tMax = Math.max(tMax,A[j]);
dp[i] = Math.max(dp[i],dp[j] + tMax *(i-j));
}
}
return dp[N];
}
}