A bike computer smooths its speed display so the number on the screen does not jump about: it shows the mean of the latest few raw readings. Write the class MovingAverage that does the smoothing.
MovingAverage(size): the display averages at most the latestsizereadings.next(val): take in the new readingvaland return what the display now shows, as a float: the mean of the latestsizereadings, or of every reading so far while fewer thansizehave arrived.
Examples
Input: ops = ["MovingAverage", "next", "next", "next", "next", "next"]
args = [[3], [4], [7], [1], [10], [-2]]
Output: [None, 4.0, 5.5, 4.0, 6.0, 3.0]
Explanation: 4/1, (4+7)/2, (4+7+1)/3, then the window drops 4: (7+1+10)/3, then it drops 7: (1+10-2)/3.
Constraints
1 <= size <= 1000- At most
10**4calls tonext - Target:
O(1)per call (do not re-sum the window each time)
Goals
- Maintain a running sum alongside a bounded deque
- Return an average over fewer than `size` values while the window fills