Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - Design ATM Machine
- //Input
- //["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"]
- //[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]
- //Output
- //[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]
- class ATM {
- var nominal: [Int]
- var counts: [Int]
- init() {
- self.nominal = [20, 50, 100, 200, 500]
- self.counts = Array.init(repeating: 0, count: 5)
- }
- // Заносим по индексам то что внесли
- func deposit(_ banknotesCount: [Int]) {
- for i in 0..<banknotesCount.count {
- counts[i] += banknotesCount[i]
- }
- }
- // Снимаем amount
- func withdraw(_ amount: Int) -> [Int] {
- var amount = amount
- var ans = Array.init(repeating: 0, count: 5)
- for i in stride(from: nominal.count-1, through: 0, by: -1) {
- // Сколько нам надо
- let need = amount/nominal[i]
- let currentBank = counts[i]
- // Выбираем минимальное - так как это то, что реально можем использовать,
- // например, если получилось что нужна 1 купюра при amount/nominal[i], а всего в банке 0, то возвращаем 0
- let canUse = min(need, currentBank)
- ans[i] = canUse
- // Если canUse = 0, то и вычитаем 0
- amount -= canUse * nominal[i]
- }
- if amount != 0 {
- return [-1]
- }
- for i in 0..<nominal.count {
- counts[i] -= ans[i]
- }
- return ans
- }
- }
- let atm = ATM()
- atm.deposit([0,1,0,1,1])
- atm.withdraw(550)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement