【前缀和】LeetCode 1031. 两个非重叠子数组的最大和

题目链接

1031. 两个非重叠子数组的最大和

思路

// TODO 先见注释

代码

class Solution {
    public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
        // 求一个前缀和
        for(int i = 1; i < nums.length; ++i){
            nums[i] += nums[i - 1];
        }

        // 初始化最终最大值的初始值,初始化firstLen子数组和最大值,初始值化secondLen子数组和最大值
        // 初始化后,是前缀和数组中满足当前子数组长度下最靠左边的几个元素值
        int result = nums[firstLen + secondLen - 1], Lmax = nums[firstLen - 1], Mmax = nums[secondLen - 1];
        for(int i = firstLen + secondLen; i < nums.length; ++i){
            // 从前往后遍历数组,找长度为firstLen的子数组最大和,此时是模拟firstLen数组在secondLen数组左边
            // nums[i - secondLen]是当前位置,M长度子数组之前的第一个元素
            Lmax = Math.max(Lmax, nums[i - secondLen] - nums[i - firstLen - secondLen]);
            // 从前往后遍历数组,找长度为secondLen的子数组最大和,此时是模拟secondLen数组在firstLen数组左边
            // nums[i - firstLen]是当前位置,firstLen长度子数组之前的第一个元素
            Mmax = Math.max(Mmax, nums[i - firstLen] - nums[i - firstLen - secondLen]);
            // 比较firstLen在左边的最大值+最近的一个secondLen子数组和,secondLen在左边并取最大值+最近的一个firstLen子数组和
            result = Math.max(result, Math.max(
                    Lmax + nums[i] - nums[i - secondLen], Mmax + nums[i] - nums[i - firstLen]));
        }

        return result;
    }
}
posted @ 2023-04-14 10:21  Frodo1124  阅读(16)  评论(0编辑  收藏  举报