Straightforward. FIFO, Queue. Size control: when reaching capacity, q.poll().

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
class MovingAverage {

Queue<Integer> q;
int size = 0, sum = 0;

/** Initialize your data structure here. */
public MovingAverage(int size) {
q = new LinkedList<>();
this.size = size;
}

public double next(int val) {
if (q.size() == size) {
sum -= q.poll();
}
q.offer(val);
sum += val;
return (double) sum / q.size();
}
}

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