Proficient Level

Implement the method coinChangeMinCoins that returns the minimum number of coins needed for an amount.

You may use each coin value any number of times. Return the fewest coins needed to make the target amount exactly.

The task is designed to test careful handling of edge cases, not only the most common input.

  • Use only the first size coin values.
  • Return 0 when the amount is 0.
  • Return -1 when the amount cannot be formed.

Example 1

Input
coins (int[]) = [1,2,5]
size (int) = 3
amount (int) = 11
Returns (int) 3

Example 2

Input
coins (int[]) = [2]
size (int) = 1
amount (int) = 3
Returns (int) -1

Example 3

Input
coins (int[]) = [1,3,4]
size (int) = 3
amount (int) = 6
Returns (int) 2

Use dynamic programming where dp[x] stores the fewest coins needed for amount x.

Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.