689. 三个无重叠子数组的最大和

image.png
class Solution {
 public int[] maxSumOfThreeSubarrays(int[] nums, int k) {
        int[] preSum = new int[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            preSum[i+1] = preSum[i] + nums[i];
        }
        //表示前i个数,分成j份的和
        int dp[][] = new int[nums.length + 2][4];
        for (int i = nums.length - k + 1; i >= 1 ; i--) {
            for (int j = 1; j < 4; j++) {
                dp[i][j] = Math.max(dp[i+1][j], dp[i+k][j-1] + preSum[i+k-1] - preSum[i-1]);
            }
        }
        int i = 1;
        int j = 3;
        int index = 0;
        int[] array = new int[3];
        while(j > 0) {
            if(dp[i][j] > dp[i+k][j-1] + preSum[i+k-1] - preSum[i-1]) {
                i++;
            } else {
                array[index++] = i-1;
                i = i + k;
                j--;
            }
        }
        return array;
    }
}

你可能感兴趣的:(689. 三个无重叠子数组的最大和)