其他分享
首页 > 其他分享> > 三个无重叠子数组的最大和

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

作者:互联网

给定数组 nums 由正整数组成,找到三个互不重叠的子数组的最大和。

每个子数组的长度为k,我们要使这3*k个项的和最大化。

返回每个区间起始索引的列表(索引从 0 开始)。如果有多个结果,返回字典序最小的一个。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-sum-of-3-non-overlapping-subarrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.Arrays;

class Solution {

    private static int getSum(int[] preSum, int l, int r) {
        if (l == 0) {
            return preSum[r];
        }

        return preSum[r] - preSum[l - 1];
    }

    public static int[] maxSumOfThreeSubarrays(int[] nums, int k) {

        if (nums == null || nums.length == 0) {
            return new int[3];
        }

        int n = nums.length;

        int[] preSum = new int[n];

        preSum[0] = nums[0];

        for (int i = 1; i < n; ++i) {
            preSum[i] = preSum[i - 1] + nums[i];
        }

        /**
         * forward[i]:直接到i左侧最优的起始位置
         */
        int[] forward = new int[n];
        /**
         * behind[i]:截止到i右侧最优的起始位置
         */
        int[] behind = new int[n];

        //        0 1 2 3 4 5

        forward[k - 1] = 0;
        for (int i = k; i < n; ++i) {
            forward[i] = getSum(preSum, i - k + 1, i) > getSum(preSum, forward[i - 1], forward[i - 1] + k - 1) ? i - k + 1 : forward[i - 1];
        }

        behind[n - k] = n - k;
        for (int i = n - k - 1; i >= 0; --i) {
            behind[i] = getSum(preSum, i, i + k - 1) >= getSum(preSum, behind[i + 1], behind[i + 1] + k - 1) ? i : behind[i + 1];
        }

        int[] ret = new int[3];
        int max = 0;

        for (int i = k; i <= n - 2 * k; ++i) {
            int sum = getSum(preSum, forward[i - 1], forward[i - 1] + k - 1) +
                    getSum(preSum, behind[i + k], behind[i + k] + k - 1) +
                    getSum(preSum, i, i + k - 1);
            if (sum > max) {
                max = sum;
                ret = new int[]{forward[i - 1], i, behind[i + k]};
            }
        }

        return ret;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 1, 2, 6, 7, 5, 1};
        int k = 2;
        int[] ints = maxSumOfThreeSubarrays(arr, k);
        Arrays.stream(ints).forEach(System.out::println);
    }
}

标签:重叠,nums,int,behind,三个,数组,forward,new,preSum
来源: https://www.cnblogs.com/tianyiya/p/15481067.html