1283. Bounded Length Best Sum
An analyst keeps the daily profit figures of a shop in the array nums, and some days are losses, so values can be negative. She wants to report the total profit of a stretch of consecutive days, but the stretch must be at least minLen days long and at most maxLen days long, with both bounds inclusive.
Return the largest total that any contiguous subarray with a length between minLen and maxLen can have, as a 64-bit integer. Since minLen never exceeds the length of the array, at least one valid stretch always exists. With up to 200000 days, aim for O(n) time and O(n) extra space, for example prefix sums together with a monotonic deque.
Example 1
- Input:
- nums = [2,-1,3,-4,5], minLen = 2, maxLen = 3
- Output:
- 4
- Explanation:
Of the stretches with length 2 or 3, (2, -1, 3) and (3, -4, 5) both sum to 4 and none is larger.
Example 2
- Input:
- nums = [-3,-1,-2], minLen = 1, maxLen = 3
- Output:
- -1
- Explanation:
Every value is negative, so the best allowed stretch is the single element -1.
Example 3
- Input:
- nums = [1,2,3,4], minLen = 4, maxLen = 4
- Output:
- 10
- Explanation:
Only the whole array has length 4, and it sums to 10.
Constraints
- 1 ≤ minLen ≤ maxLen ≤ n ≤ 2 * 105, where n is the length of
nums - -104 ≤ nums[i] ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)