Skip to content

Commit

Permalink
Add 346_Moving_Average_from_Data_Stream.java
Browse files Browse the repository at this point in the history
  • Loading branch information
seanprashad committed Apr 15, 2022
1 parent 9d363d9 commit d3fb670
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Design/346_Moving_Average_from_Data_Stream.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class MovingAverage {
private Queue<Integer> q;
private int sum;
private int maxSize;

public MovingAverage(int size) {
q = new LinkedList<>();
maxSize = size;
sum = 0;
}

public double next(int val) {
sum += val;
q.offer(val);

if (q.size() > maxSize) {
sum -= q.poll();
}

return (double) sum / q.size();
}
}

0 comments on commit d3fb670

Please sign in to comment.