LinttCode 642 : Moving Average from Data Stream
Solution to Moving Average from Data Stream Problem. Here is a nice video which explains the approach.
public class MovingAverage {
private Queue<Integer> q;
private int maxSize;
private double sum;
/*
* @param size: An integer
*/public MovingAverage(int size) {
// do intialization if necessary
maxSize = size;
q = new LinkedList<>();
}
/*
* @param val: An integer
* @return:
*/
public double next(int val) {
// write your code here
if(q.size() == maxSize) {
sum -= q.remove();
}
sum += val;
q.add(val);
return sum/q.size();
}
}