Maximum Sum of Two Non-Overlapping Subarrays
Problem statement
Given an array nums of nonnegative integers and two lengths firstLen and secondLen, choose two non-overlapping contiguous subarrays of those exact lengths. Return the largest possible sum of all elements in the two chosen subarrays.
The subarray of length firstLen may occur before or after the subarray of length secondLen. The two subarrays may touch at a boundary but must not share an index.
Function
maxSumTwoNoOverlap(nums: int[], firstLen: int, secondLen: int) → intExamples
Example 1
nums = [0,6,5,2,2,5,1,9,4]firstLen = 1secondLen = 2return = 20Choose [9] and [6,5]; their sums add to 20.
Example 2
nums = [3,8,1,3,2,1,8,9,0]firstLen = 3secondLen = 2return = 29Choose the length-three subarray [3,8,1] and the length-two subarray [8,9]. Their sums are 12 and 17.
Example 3
nums = [2,1,5,6,0,9,5,0,3,8]firstLen = 4secondLen = 3return = 31The disjoint windows [5,6,0,9] and [0,3,8] sum to 20 + 11 = 31.
Constraints
1 <= firstLen, secondLen <= 1000.firstLen + secondLen <= nums.length <= 1000.0 <= nums[i] <= 1000.