Moving Average from Data Stream
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
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
public class MovingAverage {
int count;
double sum;
int size;
Queue<Integer> queue;
public MovingAverage(int size) {
count = 0;
sum = 0;
this.size = size;
queue = new LinkedList<>();
}
public double next(int val) {
if (queue.size() < size) {
queue.add(val);
sum += val;
return sum / queue.size();
} else {
Integer remove = queue.remove();
sum -= remove;
queue.add(val);
sum += val;
return sum / queue.size();
}
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/