Average of the Last K Readings
Implement a class RecentAverage for a stream of sensor readings that reports on the most recent ones. The window is the last k readings, or all of them while there are fewer than k. Write these methods:
RecentAverage(k)starts with no readings.add(x)records the readingx. It returns nothing.average()returns the average of the readings in the window as a decimal number, or0if there are no readings.window_max()returns the largest reading in the window, or-1if there are no readings.undo()deletes the most recent reading and returns it, or returns-1if there are no readings. After an undo the window again reaches backkreadings, so an older reading may come back into it.
The tests call the methods in sequence and compare every return value, with a tolerance of 1e-6 for averages. The expected list holds null for the constructor and for add.
Example 1
RecentAverage(3)
add(4)
add(8)
average() returns 6.0
add(6)
add(10)
average() returns 8.0
window_max() returns 10
undo() returns 10
average() returns 6.0
window_max() returns 8
With k = 3 the window after four readings is 8 6 10, average 8. Undoing 10 brings 4 back, so the window is 4 8 6 with average 6 and largest 8.
Constraints
1 <= k <= 50 <= x <= 100- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.