LeetCode--689_Maximum_Sum_of_3_NonOverlapping_Subarrays

Posted dyloder

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode--689_Maximum_Sum_of_3_NonOverlapping_Subarrays相关的知识,希望对你有一定的参考价值。

原题链接:点击这里

一道很水很水的背包问题? 大概算不上背包吧QAQ 自己的dp 真的是太差劲啦,以后每天一道LeetCode 备战秋招!

package leetcode;

public class a689_Maximum_Sum_of_3_NonOverlapping_Subarrays {
    
    public static int[] maxSumOfThreeSubarrays(int[] nums, int k) {
        int [] ans = new int [3];
        int [][] dp = new int [3][nums.length+1];
        
        int [] sum = new int [nums.length+1];
        for(int j=1;j<=nums.length;j++) {
            if(j==1) {
                sum[j]=nums[j-1];
            }else {
                sum[j]+=sum[j-1]+nums[j-1];
            }
        }
        int mmx =0;
        for(int j=0;j<3;j++) {
            int max = 0;
            for(int i = k*j+1;i<=nums.length-k+1;i++) {
                if(j==0) {
                    dp[0][i] = sum[i+k-1]-sum[i-1];
                }else {
                    max = Math.max(max, dp[j-1][i-k]);
                    dp[j][i] = max+sum[i+k-1]-sum[i-1];
                    mmx = Math.max(mmx, dp[j][i]);
                }
            }
        }
        
        for(int j=2;j>=0;j--) {
            for(int i=1;i<=nums.length-k+1;i++) {
                if(dp[j][i]==mmx) {
                    ans[j]=i-1;
                    mmx -= sum[i+k-1]-sum[i-1];
                    break;
                }
            }
        }
        return ans;
    }
    
    public static void main(String[] args) {
        
        int [] nums = {1,2,1,2,6,7,5,1};
        int k = 2;
        maxSumOfThreeSubarrays(nums,k);
    }

}

Runtime: 4 ms, faster than 82.08% of Java online submissions for Maximum Sum of 3 Non-Overlapping Subarrays.

Memory Usage: 42.6 MB, less than 34.91% of Java online submissions forMaximum Sum of 3 Non-Overlapping Subarrays.
 

 

以上是关于LeetCode--689_Maximum_Sum_of_3_NonOverlapping_Subarrays的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays

leetcode689. Maximum Sum of 3 Non-Overlapping Subarrays

[LeetCode] 689. Maximum Sum of 3 Non-Overlapping Subarrays 三个非重叠子数组的最大和

英语高手请进

简易先进先出队列-自用

函数参数