The idea is to use an array int[] arr = new int[size] to keep the previous elements, use an int to keep the count of the inserting elements and a double to keep the sum. If a new element is waiting to insert:

if count < arr.size

- put the new in the array
- sum = sum + new val;
- count ++

$) cal the average

else if count >= arr.length - replace index = count % arr.length
- sum -= arr[replace index];
- arr[replace index] = new val
- sum += new val;
- avg = sum / arr.length;

Code is attached below:

```
public class MovingAverage {
private int[] arr;
int count;
double sum;
public MovingAverage(int size) {
arr = new int[size];
count = 0;
sum = 0.0;
}
public double next(int val) {
double avg = 0.0;
int size = arr.length;
if (size == 0)
return avg;
if (count < size) {
arr[count] = val;
sum += arr[count];
count += 1;
avg = sum / count;
}
else {
int replace = count % size;
sum -= arr[replace];
arr[replace] = val;
sum += val;
count += 1;
avg = sum / size;
}
return avg;
}
}
```