Fork me on GitHub

Moving Average from Data Stream

Description

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Example:

1
2
3
4
5
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class MovingAverage {
private:
int currentSize;
queue<int> q;
double sum;
int maxSize;
public:
/** Initialize your data structure here. */
MovingAverage(int size) {
maxSize = size;
sum = 0;
currentSize = 0;
}

double next(int val) {
q.push(val);
sum += val;
if (q.size() > maxSize) {
sum -= q.front();
q.pop();
}

return sum / q.size();
}
};

/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/