Problem Description
Given an integer array nums and two integers firstLen and secondLen, find the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen. The two subarrays can appear in any order (firstLen subarray may come before or after secondLen subarray) but they should not overlap.
Key Insights
- Use prefix sum to efficiently calculate the sum of any subarray.
- Consider both orders: one where the first subarray comes before the second and vice versa.
- For a fixed division, maintain a running maximum sum for the first subarray as you slide through the array.
- The sliding window technique helps to compute subarray sums in O(1) time after an O(n) pre-computation.
Space and Time Complexity
Time Complexity: O(n) – We traverse the array a constant number of times. Space Complexity: O(n) – For storing the prefix sum array.
Solution
To solve the problem, we first precompute a prefix sum array so that any subarray sum can be obtained in constant time. Then we write a helper function that computes the maximum combined sum when one subarray (with length L) comes before the other (with length M).
The approach is to slide through the array:
- For each valid position for the subarray of length M, update the maximum sum of any subarray of length L that ends before the current M begins.
- Calculate the sum of the current M subarray.
- Combine the current best L subarray sum with the M subarray sum and update the answer.
- Finally, run this helper twice – once for the order (firstLen, secondLen) and once for (secondLen, firstLen) – and take the maximum.
This method ensures that the two subarrays do not overlap and that we always keep track of the best possible split.