Loading...
Loading...
A UPI app keeps only the last k payments. When the log is full, saving a new payment drops the oldest one. undo removes the newest payment.
Write a class PaymentLog with a private long[] of size k and a private count. Give it long add(long amount) (returns the dropped amount, or 0), long undo(), long[] getRecent() (a new array, newest first), getTotal() and getCount(). Refuse amounts of 0 or less with an IllegalArgumentException, and undo on an empty log with an IllegalStateException.
pay x, undo, recent or total.pay: SAVED x or SAVED x, DROPPED y. undo: REMOVED x. recent: RECENT a b c… newest first, or NO PAYMENTS. total: TOTAL t IN c PAYMENTS. On failure: REFUSED: amount must be positive or REFUSED: nothing to undo.Example
Input
3 7 pay 100 pay 250 pay 40 pay 500 recent undo total
Output
SAVED 100 SAVED 250 SAVED 40 SAVED 500, DROPPED 100 RECENT 500 40 250 REMOVED 500 TOTAL 290 IN 2 PAYMENTS
The fourth payment drops 100; undo removes 500, leaving 250 and 40.
Try the problem first. Open one hint at a time.
Keep the payments oldest first in amounts[0..count-1]; the newest is at count - 1.
When count == k, shift every element one place left to drop amounts[0], then add at the end.
getRecent() builds a new array of size count in reverse order, so callers never touch the private array.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor