DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #240 - ATM

There's an ATM with unlimited money in bills of 10, 20, 50, 100, 200, and 500 dollars. You're given an amount of money n to withdraw with 1<=n<=1500.

Try to find the minimal number of bills that must be used to cash out n, or output -1 if it's impossible.

Example:
solve(1250) => 4 bills (500x2, 50x1, 200x1)
solve 1500 => 3 bills ($500x3)

Tests:
solve(10)
solve(550)
solve(770)

Good luck~!


This challenge comes from Sanan07 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (6)

Collapse
 
peter279k profile image
peter279k

Here is Python solution:

def solve(n): count = 0 while n - 500 >= 0: n -= 500 count += 1 while n - 200 >= 0: n -= 200 count += 1 while n - 100 >= 0: n -= 100 count += 1 while n - 50 >= 0: n -= 50 count += 1 while n - 20 >= 0: n -= 20 count += 1 while n - 10 >= 0: n -= 10 count += 1 if n != 0: return -1 return count 
Collapse
 
irgeek profile image
James Sinclair

A Python solution.

from functools import reduce sum_divmod = lambda acc, amt: (acc[0] + acc[1] // amt, acc[1] % amt) def solve(amt): count, _ = reduce(sum_divmod, (500, 200, 100, 50, 20, 10), (0, amt)) return count or -1 
Collapse
 
vidit1999 profile image
Vidit Sarkar

Here is a C++ solution,

int solve(int n){ if(n < 10 || n > 1500 || n%10 != 0) return -1; int count = 0; for(int dollar : {500,200,100,50,20,10}){ count += n/dollar; n %= dollar; } return count; } 
Collapse
 
patricktingen profile image
Patrick Tingen

Progress 4GL solution:

FUNCTION solve RETURNS INTEGER (amount AS INTEGER): DEFINE VARIABLE bill AS INTEGER EXTENT 6 INITIAL [500,200,100,50,20,10] NO-UNDO. DEFINE VARIABLE needed AS INTEGER NO-UNDO. DEFINE VARIABLE i AS INTEGER NO-UNDO. DO i = 1 TO EXTENT(bill): needed = needed + TRUNCATE(amount / bill[i],0). amount = amount - (bill[i] * TRUNCATE(amount / bill[i],0)). END. RETURN needed. END FUNCTION. MESSAGE solve(1250) SKIP solve(1500) VIEW-AS ALERT-BOX INFORMATION BUTTONS OK. 
Collapse
 
jeffjadulco profile image
Jeff Jadulco
const bills = [500, 200, 100, 50, 20, 10] const solve = (money) => { if (money < 1 || money > 1500) return -1 let numBills = 0 bills.forEach(bill => { const div = Math.floor(money / bill) money -= div * bill numBills += div }) return numBills > 0 ? numBills : -1 } 
Collapse
 
mxb profile image
mxb

Implementation in Frink

// https://dev.to/thepracticaldev/daily-challenge-240-atm-109c solve[amount] := { bills = [500, 200, 100, 50, 20, 10] count = 0 if amount < 1 or amount > 1500 return -1 for b = bills { nbills = floor[amount / b] amount = amount - (nbills b) count = count + nbills } return count }