Problem Description
Design and implement an ATM machine that supports depositing and withdrawing money using five banknote denominations ($20, $50, $100, $200, and $500). The ATM begins empty and allows deposits of banknotes in the fixed order. For withdrawals, the ATM follows a greedy strategy: it always attempts to use as many larger denomination banknotes as possible (in the strict ordering from highest to lowest) before attempting smaller ones. If the requested withdrawal amount cannot be exactly provided by following this strict greedy ordering, the request is rejected (no banknotes are dispensed).
Key Insights
- The ATM only holds banknotes in 5 fixed denominations.
- Depositing updates the count of banknotes directly.
- Withdrawing uses a greedy approach by iterating over the banknotes in descending order.
- If after using as many as possible from each denomination the requested amount is not met exactly, the transaction is canceled.
- The strict ordering for withdrawal means that even if an alternative combination exists, it must follow the descent order (largest first).
Space and Time Complexity
Time Complexity: O(1) per deposit/withdraw operation (constant number of denominations to process)
Space Complexity: O(1) (only fixed arrays for denominations and counts are used)
Solution
We maintain an internal array to store the count of banknotes for denominations $20, $50, $100, $200, and $500. For deposits, we simply update these counts. For withdrawals, we simulate the withdrawal process using a greedy approach: starting from $500 and moving downwards to $20, we determine the maximum number of banknotes we can use for each denomination without exceeding both the needed amount and what is available. If the entire amount is matched exactly, we update the internal state by deducting the used banknotes; otherwise, we leave the internal state unchanged and return [-1]. This ensures that no withdrawal is partially processed.