Given an integer array nums and two integers firstLen and secondLen, return _the maximum sum of elements in two non-overlappingsubarrays with lengths _firstLenandsecondLen.
The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.
To maximize the sum of two non-overlapping subarrays, try both possible orders: firstLen before secondLen and secondLen before firstLen. For each order, use sliding windows to track the best sum for the first subarray and combine it with the current sum of the second subarray.
classSolution {
funmaxSumTwoNoOverlap(nums: IntArray, firstLen: Int, secondLen: Int): Int {
funhelper(l: Int, r: Int): Int {
val n = nums.size
var maxL = 0; var sumL = 0; var sumR = 0; var ans = 0for (i in0 until l) sumL += nums[i]
for (i in l until l + r) sumR += nums[i]
maxL = sumL
ans = maxOf(ans, maxL + sumR)
for (i in l + r until n) {
sumL += nums[i - r] - nums[i - r - l]
maxL = maxOf(maxL, sumL)
sumR += nums[i] - nums[i - r]
ans = maxOf(ans, maxL + sumR)
}
return ans
}
return maxOf(helper(firstLen, secondLen), helper(secondLen, firstLen))
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defmaxSumTwoNoOverlap(self, nums: list[int], firstLen: int, secondLen: int) -> int:
defhelper(l: int, r: int) -> int:
n = len(nums)
maxL = sumL = sumR = ans =0 sumL = sum(nums[:l])
sumR = sum(nums[l:l+r])
maxL = sumL
ans = max(ans, maxL + sumR)
for i in range(l + r, n):
sumL += nums[i - r] - nums[i - r - l]
maxL = max(maxL, sumL)
sumR += nums[i] - nums[i - r]
ans = max(ans, maxL + sumR)
return ans
return max(helper(firstLen, secondLen), helper(secondLen, firstLen))