689. 三个无重叠子数组的最大和
作者:互联网
给你一个整数数组 nums 和一个整数 k ,找出三个长度为 k 、互不重叠、且全部数字和(3 * k 项)最大的子数组,并返回这三个子数组。
以下标的数组形式返回结果,数组中的每一项分别指示每个子数组的起始位置(下标从 0 开始)。如果有多个结果,返回字典序最小的一个。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-sum-of-3-non-overlapping-subarrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private int[] getPreSum(int[] nums) {
int[] preSum = new int[nums.length];
preSum[0] = nums[0];
for (int i = 1; i < nums.length; ++i) {
preSum[i] = preSum[i - 1] + nums[i];
}
return preSum;
}
private int getRegionSum(int[] preSum, int left, int right) {
return left == 0 ? preSum[right] : preSum[right] - preSum[left - 1];
}
public int[] maxSumOfThreeSubarrays(int[] nums, int k) {
if (nums == null || nums.length < 3 * k) {
return new int[3];
}
int n = nums.length;
int[] preSum = getPreSum(nums);
int[] forward = new int[n];
int[] behind = new int[n];
forward[k - 1] = 0;
for (int i = k; i < n; ++i) {
forward[i] = getRegionSum(preSum, forward[i - 1], forward[i - 1] + k - 1) >=
getRegionSum(preSum, i - k + 1, i) ? forward[i - 1] : i - k + 1;
}
// 0 1 2 3
behind[n - k] = n - k;
for (int i = n - k - 1; i >= 0; --i) {
behind[i] = getRegionSum(preSum, i, i + k - 1) >=
getRegionSum(preSum, behind[i + 1], behind[i + 1] + k - 1) ? i : behind[i + 1];
}
int[] ans = {};
int max = Integer.MIN_VALUE;
for (int i = k; i < n - 2 * k + 1; ++i) {
int sum = getRegionSum(preSum, forward[i - 1], forward[i - 1] + k - 1) +
getRegionSum(preSum, i, i + k - 1) +
getRegionSum(preSum, behind[i + k], behind[i + k] + k - 1);
if (sum > max) {
max = sum;
ans = new int[]{forward[i - 1], i, behind[i + k]};
}
}
return ans;
}
}
标签:重叠,nums,int,behind,689,数组,forward,preSum,getRegionSum 来源: https://www.cnblogs.com/tianyiya/p/15845664.html