// 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 public class MovingAverage { private int[] array; private int count; private boolean isFull; private double total; /** Initialize your data structure here. */ public MovingAverage(int size) { array = new int[size]; total = 0; count = 0; isFull = false; } public double next(int val) { if (count < array.length && !isFull) { array[count] = val; total += val; count++; return total / count; } if (count == array.length) { isFull = true; count = 0; } total = total - array[count] + val; array[count] = val; count++; return total / array.length; } }