Back to challenges
Easy 0 solved 0% acceptance

Cash: Fewest Coins

Give change with as few U.S. coins as possible.

What you'll learn

  • Pick the largest coin first
  • Use division and remainder for counts
  • See when greedy change is optimal

Problem

A cashier gives change using quarters (25¢), dimes (10¢), nickels (5¢) and pennies (1¢). Always using the largest coin that still fits gives the fewest coins for these values. Return how many coins are needed for cents.

Implement fewest_coins(cents).

Input

cents: The change owed in cents.

Output

Return the minimum number of coins.

Constraints

0 ≤ cents ≤ 1,000,000

Examples

Example 1
Input:
cents = 41

Expected output:
expected = 4
Input:
long long cents = 41;

Expected output:
long long expected = 4;
Input:
long cents = 41;

Expected output:
long expected = 4;

Explanation

One quarter (25), one dime (35), one nickel (40) and one penny (41): 4 coins.

Example 2
Input:
cents = 0

Expected output:
expected = 0
Input:
long long cents = 0;

Expected output:
long long expected = 0;
Input:
long cents = 0;

Expected output:
long expected = 0;

Explanation

No change is owed: 0 coins.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Use the largest coin denomination that fits, then move to smaller coins with the remaining amount.

Hint 2

Divide and take remainders to count each coin type efficiently.

Hint 3

Be careful with exact multiples so you do not leave a leftover amount by mistake.

Expected complexity

O(1) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.