LeetCode - 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.
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

Java Solution:
class MovingAverage {

    /** Initialize your data structure here. */
    private Queue<Integer> q;
    private double sum;
    private int maxSize;
    public MovingAverage(Integer size) {
        q = new LinkedList<Integer>();
        maxSize = size;
        sum = 0;
    }
    
    public double next(int val) {
        if(q.size() != maxSize){
            q.offer(val);
            sum+=val;
            return sum / q.size();
        }else{
            sum-=q.peek(); // subtracting from sum before removing the first element
            q.poll();
            q.offer(val);
            sum+=val;
            return sum / q.size();
        }
    }
}

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

No comments:

Post a Comment

Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...