Problem 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.
题解:dp
for(j = i; j > i - K && j >= 0; j--) { maxInPart = Math.max(maxInPart, A[j]); int prev = 0; if(j - 1 >= 0) prev = dp[j - 1]; dp[i] = Math.max(dp[i], prev + maxInPart * (i - j + 1)); }
时间复杂度:O(kn), 空间复杂度:O(n)
class Solution { public int maxSumAfterPartitioning(int[] A, int K) { int n = A.length; int[] dp = new int[n]; dp[0] = A[0]; for(int i = 1; i < n; i++) { int j = i; int maxInPart = A[j]; for(j = i; j > i - K && j >= 0; j--) { maxInPart = Math.max(maxInPart, A[j]); int prev = 0; if(j - 1 >= 0) prev = dp[j - 1]; dp[i] = Math.max(dp[i], prev + maxInPart * (i - j + 1)); } } return dp[n - 1]; } }