Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. Implement the MovingAverage class: - MovingAverage(int size) Initializes the object with the size of the window size. - double next(int val) Returns the moving average of the last size values of the stream.
Example 1
Input: operations = ["MovingAverage","next","next","next","next"], arguments = [[3],[1],[10],[3],[5]]
Output: [null,1.0,5.5,4.666666666666667,6.0]
Explanation: The window holds at most 3 values. [1] → 1.0. [1,10] → 5.5. [1,10,3] → 14 / 3 ≈ 4.667. Adding 5 pushes out the 1, so [10,3,5] → 18 / 3 = 6.0.
Example 2
Input: operations = ["MovingAverage","next"], arguments = [[1],[4]]
Output: [null,4.0]
Explanation: With a window of 1, the average is just the latest value, 4.
Example 3
Input: operations = ["MovingAverage","next","next"], arguments = [[2],[5],[5]]
Output: [null,5.0,5.0]
Explanation: The window holds 2 values. First [5] averages 5, then [5,5] also averages 5.
Keep the window in a queue and a running total. On each value, add it; if the window overflows, subtract the value that left. The average is total / current window size.
Run checks all cases above. Submit evaluates all test cases.