1302. Window Stats Board
Build a small dashboard widget, WindowStatsBoard, that watches a stream of integer readings and reports statistics over only the most recent k readings. The constructor takes k, the window size. The method push(x) records a new reading and forgets the oldest one once more than k readings are held; before k readings have arrived, the window simply contains every reading pushed so far. The method windowMax() returns the largest value in the window, windowMin() the smallest, and windowSum() the sum of all values in the window as a 64-bit integer. Queries are only made after at least one push. Every operation should run in amortised O(1) time, keeping two monotonic deques beside a queue of the values.
Example 1
- Input:
- operations = ["WindowStatsBoard","push","push","windowMax","windowMin","windowSum","push","push","windowMax","windowMin","windowSum"]arguments = [[3],[5],[2],[],[],[],[8],[1],[],[],[]]
- Output:
- [null,null,null,5,2,7,null,null,8,1,11]
- Explanation:
After pushing 5 and 2 the window is [5, 2] so the stats are 5, 2 and 7; after pushing 8 and 1 with k = 3 the window is [2, 8, 1] so the stats are 8, 1 and 11.
Example 2
- Input:
- operations = ["WindowStatsBoard","push","windowMax","windowMin","windowSum","push","windowMax","windowMin","windowSum","push","windowMax","windowMin","windowSum"]arguments = [[2],[4],[],[],[],[4],[],[],[],[9],[],[],[]]
- Output:
- [null,null,4,4,4,null,4,4,8,null,9,4,13]
- Explanation:
With k = 2 the window holds just the single 4 at first, then two 4s, and after pushing 9 the window is [4, 9] giving max 9, min 4, sum 13.
Example 3
- Input:
- operations = ["WindowStatsBoard","push","windowMax","windowMin","windowSum","push","windowMax","windowMin","windowSum"]arguments = [[10],[-3],[],[],[],[7],[],[],[]]
- Output:
- [null,null,-3,-3,-3,null,7,-3,4]
- Explanation:
With k = 10 nothing is ever forgotten here, so the window is [-3] and then [-3, 7] giving max 7, min -3 and sum 4.
Constraints
1 ≤ k ≤ 104
At most 2000 calls in total
-109 ≤ x ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Input
- Each case is an operation log.
operationsnames the class first and then each method call;argumentsholds the arguments for each, in the same order. Your answer is one list with a result per operation -nullfor the constructor and for methods that return nothing.
Expected complexity
- Time
- O(1) amortised per call
- Space
- O(k)