346. Moving Average from Data Stream
Problem
Compute the moving average of all integers in a sliding window of size k.
Design a data structure that supports:
MovingAverage(size): Initialize with window size k.next(val): Add a new value and return the moving average of the last k values.
The moving average is the average of the last k values in the stream.
Examples
Input: [["MovingAverage","next","next","next","next"],[[3],[1],[10],[3],[5]]]
Output: [null,1,5.5,4.666666666666667,6]
Input: [["MovingAverage","next","next","next","next"],[[3],[1],[10],[3],[5]]]
Output: [null,1,5.5,4.666666666666667,6]
Hints
Use a queue to maintain the last k values.
Keep a running sum for O(1) average computation.
Remove the oldest value when the window exceeds size k.
Related Problems
346. Moving Average from Data Stream
Compute the moving average of all integers in a sliding window of size k.