Maximum Sum of Two Non-Overlapping Subarrays - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2
›
Output:
20
💡 Note:
One choice: secondLen subarray [0,6] with sum 6, firstLen subarray [9] with sum 9. Total = 6 + 9 = 15. Better choice: secondLen subarray [5,1] with sum 6, firstLen subarray [9] with sum 9. Actually optimal: secondLen [9,4] = 13, firstLen [6] = 6, but they overlap. Best non-overlapping: firstLen [9] = 9, secondLen [0,6] = 6. Wait - let me recalculate: nums[7:9] = [9,4] sum=13, nums[0:2] = [0,6] sum=6, total=19. But actually nums[1:3]=[6,5] sum=11, nums[7]=[9] sum=9, total=20.
Example 2 — Equal Lengths
$
Input:
nums = [5,5,4,9,4,1,3,1], firstLen = 2, secondLen = 2
›
Output:
23
💡 Note:
Best firstLen=[9,4] at indices 3-4 with sum 13, best non-overlapping secondLen=[5,5] at indices 0-1 with sum 10. Total = 13 + 10 = 23.
Example 3 — Small Array
$
Input:
nums = [1,2,1,2,6,7,5,1], firstLen = 2, secondLen = 3
›
Output:
21
💡 Note:
Best combination: secondLen=[6,7,5] at indices 4-6 with sum 18, firstLen=[1,2] at indices 0-1 with sum 3. Total = 18 + 3 = 21.
Constraints
- 1 ≤ firstLen, secondLen ≤ 1000
- 2 ≤ nums.length ≤ 1000
- firstLen + secondLen ≤ nums.length
- 0 ≤ nums[i] ≤ 1000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code