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.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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];
    }
}

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄