Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

moving average from data stream leetcode solution

 

Javascript program Moving Average from data Stream Leetcode solution

 
var MovingAverage = function(size) {
    this.size = size;
    this.slidingWindow = [];
    this.sum = 0
};

/**
* @param {number} val
* @return {number}
*/

MovingAverage.prototype.next = function(val) {
    this.slidingWindow.push(val);
    let slidingWindowSize = this.slidingWindow.length;
     
    if (slidingWindowSize this.size) {
        this.sum += val;
        return this.sum / slidingWindowSize;
    } else {
        let element = this.slidingWindow.shift();
        this.sum += val
        this.sum -= element;
        return this.sum / this.size;
    }
};


 
Time Complexity : O(n)
Space Complexity : O(n)



This post first appeared on CodeforJS, please read the originial post: here

Share the post

moving average from data stream leetcode solution

×

Subscribe to Codeforjs

Get updates delivered right to your inbox!

Thank you for your subscription

×