Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
Input: nums =[1,2,1,2,6,7,5,1], k =2Output: [0,3,5]Explanation: Subarrays [1,2],[2,6],[7,5] correspond to the starting indices [0,3,5].We could have also taken [2,1], but an answer of [1,3,5] would be lexicographically larger.
Example 2:
1
2
Input: nums =[1,2,1,2,1,2,1,2,1], k =2Output: [0,2,4]
publicclassSolution {
publicint[]maxSumOfThreeSubarrays(int[] nums, int k) {
int n = nums.length;
int[] sum =newint[n - k + 1];
// Compute sum of each k-length subarrayint windowSum = 0;
for (int i = 0; i < k; i++) {
windowSum += nums[i];
}
sum[0]= windowSum;
for (int i = 1; i <= n - k; i++) {
windowSum = windowSum - nums[i - 1]+ nums[i + k - 1];
sum[i]= windowSum;
}
// Find the left index with maximum sumint[] left =newint[n - k + 1];
int bestLeft = 0;
left[0]= 0;
for (int i = 1; i <= n - k; i++) {
if (sum[i]> sum[bestLeft]) {
bestLeft = i;
}
left[i]= bestLeft;
}
// Find the right index with maximum sumint[] right =newint[n - k + 1];
int bestRight = n - k;
right[n - k]= n - k;
for (int i = n - k - 1; i >= 0; i--) {
if (sum[i]>= sum[bestRight]) {
bestRight = i;
}
right[i]= bestRight;
}
// Find the max sum of three non-overlapping subarraysint maxSum = 0;
int[] result =newint[3];
for (int i = k; i <= n - 2 * k; i++) {
int l = left[i - k], r = right[i + k];
int total = sum[l]+ sum[i]+ sum[r];
if (total > maxSum) {
maxSum = total;
result[0]= l;
result[1]= i;
result[2]= r;
}
}
return result;
}
}
classSolution : defmaxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
sum = [0] * (n - k +1)
#Compute sum of each k - length subarray window_sum = sum(nums[:k])
sum[0] = window_sum
for i in range(1, n - k +1):
window_sum = window_sum - nums[i -1] + nums[i + k -1]
sum[i] = window_sum
#Find the left index with maximum sum left = [0] * (n - k +1)
best_left =0 left[0] =0for i in range(1, n - k +1):
if sum[i] > sum[best_left]:
best_left = i
left[i] = best_left
#Find the right index with maximum sum right = [0] * (n - k +1)
best_right = n - k
right[n - k] = n - k
for i in range(n - k -1, -1, -1):
if sum[i] >= sum[best_right]:
best_right = i
right[i] = best_right
#Find the max sum of three non - overlapping subarrays max_sum =0 result = [0] *3for i in range(k, n -2* k +1):
l = left[i - k]
r = right[i + k]
total = sum[l] + sum[i] + sum[r]
if total > max_sum:
max_sum = total
result[0] = l
result[1] = i
result[2] = r
return result