Moving Average from Data Stream
The problem is about calculating the moving average of the last size
values in a stream of integers. We can implement the MovingAverage class by utilizing a queue (FIFO) data structure to maintain the window of the last size
values and compute the moving average efficiently.
Here’s a guide to implementing this class:
Initialize the Class Variables: The constructor will initialize the
size
and a queue to keep track of the integers in the current window. You can also maintain the sum of the numbers in the window for efficient calculation.Implement the next Method:
- Add the Value to the Queue: Add the incoming value to the queue.
- Update the Sum: Add the value to the sum of the window.
- Check Window Size: If the window size exceeds
size
, remove the oldest value from the queue and subtract it from the sum. - Calculate and Return the Average: Return the sum divided by the current window size.
Here’s the code:
|
|
Explanation:
- The
deque
data structure ensures efficient addition and removal of elements from both ends. - The
window_sum
variable keeps track of the sum of the elements in the current window, allowing for quick average calculation. - When a new value is added to the queue and the window size exceeds the given
size
, the oldest value is removed from the queue and subtracted fromwindow_sum
. - The moving average is returned by dividing
window_sum
by the current window size.
This solution meets the constraints and provides an efficient way to calculate the moving average in a sliding window.
Given: stream of integers and window size Unknown: Moving Average
What is moving average?
- summation of the elements within the window size / window size
Invariant - Cannot exceed the window size window size <= size
Time: O(N) Space: O(M)
|
|