1754. Window Top-K Total
A weather station records one reading per day in nums. For every block of w consecutive days, the analyst wants the total of the k highest readings inside that block; readings equal in value are counted separately, and negative readings are allowed. Return a long[] of length n - w + 1 whose i-th entry is that total for the block starting at index i. Re-sorting every block is too slow: the intended solution slides the block one day at a time and keeps the data organised so that each slide costs O(log n), for O(n log n) time and O(n) space overall. Totals can reach 10^14, so use 64-bit integers. Here n is at most 10^5 and 1 <= k <= w <= n.
Example 1
- Input:
- nums = [4,-2,7,1,5], w = 3, k = 2
- Output:
- [11,8,12]
- Explanation:
The windows are [4,-2,7], [-2,7,1], [7,1,5]; the two largest of each sum to 11, 8 and 12.
Example 2
- Input:
- nums = [3,3,3,3], w = 2, k = 1
- Output:
- [3,3,3]
- Explanation:
Every window holds two 3s and the single largest value is 3, so each window gives 3.
Constraints
1 ≤ k ≤ w ≤ n ≤ 105 where n = nums.length; -109 ≤ nums[i] ≤ 109.
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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)