Leetcode 2241: Design an ATM Machine

grid47
grid47
Exploring patterns and algorithms
Mar 27, 2024 7 min read

Design an ATM machine that can handle deposits and withdrawals of five denominations: $20, $50, $100, $200, and $500. When withdrawing, the machine always tries to use the highest denominations available first. Implement methods to deposit money and withdraw specified amounts.
Problem
Approach
Steps
Complexity
Input: The input consists of operations performed on the ATM, including deposits and withdrawals.
Example: Input ["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"] [[], [[1,2,3,0,1]], [250], [[0,1,0,1,2]], [570], [1000]]
Constraints:
• banknotesCount.length == 5
• 0 <= banknotesCount[i] <= 10^9
• 1 <= amount <= 10^9
• At most 5000 calls in total to withdraw and deposit.
• Sum of banknotesCount[i] in all deposits doesn't exceed 10^9.
Output: Output the result of each operation: null for deposits, an array of withdrawn banknotes for successful withdrawals, or [-1] if a withdrawal cannot be fulfilled.
Example: Output [null, null, [0,0,2,0,0], null, [-1], [-1]]
Constraints:
• For successful withdrawals, the output array must be of length 5 and reflect the denominations used in the order $20, $50, $100, $200, $500.
• If a withdrawal cannot be fulfilled, output [-1].
Goal: Simulate the ATM operations while adhering to the constraints of prioritizing higher denominations for withdrawals.
Steps:
• Initialize the ATM with five denominations and their counts set to 0.
• For deposits, update the count of each denomination.
• For withdrawals, calculate the maximum possible banknotes of each denomination that can be used while satisfying the total amount.
• If the amount cannot be withdrawn exactly, return [-1] without modifying the ATM's state.
Goal: Conditions that must be followed during deposit and withdrawal operations.
Steps:
• Deposits add to the current count of banknotes in the ATM.
• Withdrawals must minimize the number of notes used by prioritizing larger denominations.
• Withdrawals are only allowed if the exact amount can be fulfilled using the available banknotes.
Assumptions:
• The ATM starts with no banknotes.
• Withdrawals are rejected if the exact amount cannot be formed.
• Deposits do not specify the order of operations; they directly add banknotes to the ATM.
Input: Input ["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"] [[], [[1,1,0,0,1]], [300], [[0,0,2,1,0]], [750], [70]]
Explanation: 1. ATM is initialized. 2. Deposit adds $20 (1), $50 (1), and $500 (1). 3. Withdraw 300 uses $50 (1) and $500 (1). 4. Deposit adds $100 (2) and $200 (1). 5. Withdraw 750 fails as exact denominations are not available. 6. Withdraw 70 fails as $20 and $50 cannot fulfill the amount.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus