Maximum Subarray Sum II
You are given an array nums of integers and two limits, a and b. Your task is to find the maximum possible sum of any contiguous subarray whose length is strictly between a and b (inclusive).
The array can contain negative numbers, positive numbers, and zeros. You must process the array and return the largest sum that satisfies the length constraints.
Example 1:
Input: nums: [-1, 3, -2, 5, 3, -5, 2, 2], a: 1, b: 2
Output: 8
Explanation:
We can only look at subarrays of length 1 or 2.
- Length 1 maximums: 5, 3, etc.
- Length 2 maximums: (-1 + 3) = 2, (3 - 2) = 1, (5 + 3) = 8.
The maximum sum across all valid lengths is 8 (from the subarray [5, 3]).
Example 2:
Input: nums: [-5, -2, -8, -1], a: 2, b: 3
Output: -7
Explanation:
We must choose a subarray of length 2 or 3.
- Length 2 sums: (-5 + -2) = -7, (-2 + -8) = -10, (-8 + -1) = -9.
- Length 3 sums: (-5 + -2 + -8) = -15, (-2 + -8 + -1) = -11.
The maximum sum among all valid choices is -7.
Now Your Turn!
Pick the correct output for the given inputInput: nums: [10, -5, 20], a:2, b:3
(What is the maximum sum for this array with the given bounds?)
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= nums.length <= 200,000
- 1 <= a <= b <= nums.length
- -109 <= nums[i] <= 109