Given a stream of integers and a window size, calculate the moving average of all…
- User
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Implement the
MovingAverageclass:MovingAverage(int size)Initializes the object with the size of the windowsize.double next(int val)Returns the moving average of the lastsizevalues of the stream.
Example 1:
Input [ "MovingAverage ", "next ", "next ", "next ", "next "] [[3], [1], [10], [3], [5]] Output [null, 1.0, 5.5, 4.66667, 6.0]
Explanation MovingAverage movingAverage = new MovingAverage(3); movingAverage.next(1); // return 1.0 = 1 / 1 movingAverage.next(10); // return 5.5 = (1 + 10) / 2 movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3
Constraints:
1 <= size <= 1000-105 <= val <= 105- At most
104calls will be made tonext.
- Assistantpython
from collections import deque class MovingAverage: def __init__(self, size: int): self.queue = deque() self.maxSize = size self.sum = 0.0 def next(self, val: int) -> float: if len(self.queue) == self.maxSize: self.sum -= self.queue.popleft() self.queue.append(val) self.sum += val return self.sum / len(self.queue)explanation The algorithm uses a queue to maintain a sliding window of the last
sizevalues of the stream. When a new value is added, the algorithm checks the size of the queue. If it equalssize, the oldest value is removed from the front of the queue by updating the sum and popping it. Then, the new value is added to the back of the queue, and the sum is updated. The average is returned by dividing the sum by the number of values currently in the queue. The time complexity of thenextfunction is O(1).