Moving Average from Data Stream
Problem
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 windowsize
.double next(int val)
Returns the moving average of the lastsize
values of the stream.
Constraints
1 <= size <= 1000
-105 <= val <= 105
- At most
104
calls will be made tonext
.
Solution
The problem Moving Average from Data Stream
can be solved by implementing a cache using queue to keep track of integers within a window size.
Implementation
class MovingAverage
{
private:
int capacity;
double sum;
queue<int> cache;
public:
MovingAverage(int size)
{
capacity = size;
sum = 0;
}
double next(int val)
{
if (cache.size() == capacity)
{
sum -= cache.front();
cache.pop();
}
sum += val;
cache.push(val);
return sum / cache.size();
}
};
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage* obj = new MovingAverage(size);
* double param_1 = obj->next(val);
*/