1763. Top Stretch Totals
A corner shop records its sales for n consecutive days in the array nums; every entry is positive. A stretch is a run of consecutive days, identified by its first and last day (l, r) with l <= r, and its total is the sum of nums[l..r]. Two different stretches with the same total are still two separate stretches.
Return the k largest stretch totals among all n(n+1)/2 stretches, in non-increasing order, as a long array of length k. Totals can exceed 32 bits. Enumerating every stretch is too slow in general; use a heap so that the work depends on n and k only: O(n + k log k) time and O(n + k) space.
Example 1
- Input:
- nums = [3,1,2], k = 4
- Output:
- [6,4,3,3]
- Explanation:
The six stretch totals are 6, 4, 3, 3, 2 and 1 (the two 3s come from different stretches), so the four largest are 6, 4, 3, 3.
Example 2
- Input:
- nums = [5], k = 1
- Output:
- [5]
- Explanation:
There is one stretch, the single day, with total 5.
Example 3
- Input:
- nums = [2,2,2], k = 3
- Output:
- [6,4,4]
- Explanation:
The totals are 6, 4, 4, 2, 2, 2; the top three are 6, 4, 4.
Constraints
1 ≤ n ≤ 105, where n = nums.length
1 ≤ nums[i] ≤ 109
1 ≤ k ≤ min(2000, n(n+1)/2)
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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n + k log k)
- Space
- O(n + k)