Moving Average from Data Stream

ID: 642; easy

Solution 1 (Java)

public class MovingAverage {

    Queue<Integer> q;
    double sum;
    int size;

    /*
    * @param size: An integer
    */
    public MovingAverage(int size) {
        q = new ArrayDeque<>();
        sum = 0;
        this.size = size;
    }

    /*
     * @param val: An integer
     * @return:  
     */
    public double next(int val) {
        sum += val;
        if (q.size() == size) {
            int pollVal = q.poll();
            sum -= pollVal;
        }
        q.offer(val);
        return sum / q.size();
    }
}

Last updated