oneby7

Greedy The best choice now

502. Fewest Coins with Greedy

Easy

There are coins of ten values: 1, 2, 5, 10, 20, 50, 100, 200, 500 and 2000. You have as many coins of each value as you want.

Given an integer amount, return the fewest coins that add up to exactly amount. Return them as a list of coin values, from the largest to the smallest.

Example 1

Input: amount = 4746

Output: [2000,2000,500,200,20,20,5,1]

Explanation: Two 2000s make 4000. Then 500, 200, two 20s, 5 and 1 make the other 746. No list of fewer than eight coins adds up to 4746.

Example 2

Input: amount = 1999

Output: [500,500,500,200,200,50,20,20,5,2,2]

Explanation: A 2000 is too big, so every coin is smaller: three 500s, two 200s, a 50, two 20s, a 5 and two 2s. That is eleven coins.

Example 3

Input: amount = 2000

Output: [2000]

Explanation: One coin is worth exactly the amount.

Check your understanding

Work out the answer for this input before you write any code.

amount = 9

Constraints

  • 1 ≤ amount ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.