Maximum Sum of Two Non-Overlapping Subarrays Problem
Description
LeetCode Problem 1031.
Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen.
The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2
Output: 20
Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.
Example 2:
Input: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2
Output: 29
Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.
Example 3:
Input: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3
Output: 31
Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.
Constraints:
1 <= firstLen, secondLen <= 10002 <= firstLen + secondLen <= 1000firstLen + secondLen <= nums.length <= 10000 <= nums[i] <= 1000
Solution
Approach: Prefix Sums and the Best Left Subarray
The two subarrays either have the firstLen one on the left or the secondLen one on the left. We solve "a subarray of length L before a subarray of length M" and take the better of the two orders.
Build prefix sums prefix[i] = nums[0] + ... + nums[i - 1], so any subarray sum is a difference of two prefix sums. Then let the right subarray start at index i, for every i from L to n - M:
- The left subarray must end at or before
i. KeepbestLeft, the largest sum of a length-Lsubarray ending at or beforei. Whenimoves one step right, only one new candidate appears,nums[i - L .. i - 1], so we updatebestLeftwith its sum. - The right subarray
nums[i .. i + M - 1]plusbestLeftis the best total with the right part starting ati.
The largest of these totals is the answer for this order. Forgetting the second order (secondLen first, then firstLen) is the usual mistake: in example 1 the best choice puts the length-2 subarray [6,5] before the length-1 subarray [9].
Complexity: O(n) time and O(n) extra space for the prefix sums.
class Solution:
def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int:
n = len(nums)
prefix = [0] * (n + 1) # prefix[i] = nums[0] + ... + nums[i - 1]
for i, x in enumerate(nums):
prefix[i + 1] = prefix[i] + x
def best(left_len: int, right_len: int) -> int:
"""Best sum with a left_len subarray somewhere before a right_len subarray."""
result = best_left = 0
# The right subarray is nums[i : i + right_len]; the left one must end at or before i.
for i in range(left_len, n - right_len + 1):
best_left = max(best_left, prefix[i] - prefix[i - left_len])
result = max(result, best_left + prefix[i + right_len] - prefix[i])
return result
return max(best(firstLen, secondLen), best(secondLen, firstLen))