Maximum Sum of Two Non-Overlapping Subarrays
Master this topic with zero to advance depth.
Maximum Sum of Two Non-Overlapping Subarrays
To find two non-overlapping subarrays with lengths L and M that give the maximum sum, we consider two cases: subarray L comes before M, or M comes before L. We use prefix sums to calculate subarray sums in O(1) and track the maximum sum seen so far.
Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of two non-overlapping subarrays with lengths firstLen and secondLen. The subarrays must be non-overlapping, meaning they don't share any index.
Visual Representation
nums = [0, 6, 5, 2, 2, 5, 1, 9, 4], firstLen = 1, secondLen = 2
Possible Selections:
[6] and [1, 9] -> Sum = 6 + 10 = 16
[0] and [9, 4] -> Sum = 0 + 13 = 13
[9] and [6, 5] -> Sum = 9 + 11 = 20 (MAX!)Examples
One choice of subarrays is [9] with length 1, and [6,5] with length 2.
One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.
Level I: Brute Force (Iterate All Subarrays)
Intuition
Iterate through all possible start positions for the first subarray of length firstLen. For each position, iterate through all possible start positions for the second subarray of length secondLen. Check if the two subarrays overlap; if not, calculate their sum and update the maximum.
Detailed Dry Run
| Sub1 (L=1) | Sub2 (M=2) | Total Sum | Max |
|---|---|---|---|
| [9] at i=7 | [0,6] at j=0 | 9+11=20 | 20 |
| [9] at i=7 | [4] at j=8 | OOB | 20 |
Level II: Better Solution (Prefix Sum + Nested Loops)
Intuition
Use prefix sums to calculate any subarray sum in O(1) time. This eliminates the inner loop for sum calculation but still requires O(N²) to check all pairs of non-overlapping subarrays.
Detailed Dry Run
| prefix[i+L]-prefix[i] | prefix[j+M]-prefix[j] | Action |
|---|---|---|
| sum(1) = 9 | sum(2) = 11 | total = 20 |
| sum(1) = 4 | sum(2) = 10 | total = 14 |
Level III: Optimal Solution (Prefix Sum + Sliding Window)
Intuition
Maintain the maximum sum of a subarray of length L seen so far as we iterate through possible positions of a following subarray of length M. We repeat this with L following M to cover both cases. This gives O(N) by visiting each element once.
Detailed Dry Run
Sliding Window Max Sum (L=1, M=2)
nums = [0, 6, 5, 2, 2, 5]
Pass 1 (L before M):
[0] [6, 5] 2 2 5 -> sumL=0, maxL=0, sumM=11, res=11
0 [6] [5, 2] 2 5 -> sumL=6, maxL=6, sumM=7, res=max(11, 13)=13
0 6 [5] [2, 2] 5 -> sumL=5, maxL=6, sumM=4, res=max(13, 10)=13Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.