Tutorialspoint
Problem
Solution
Submissions

Coin Change Problem

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to find the minimum number of coins required to make up a given amount. You are given an array of positive integers representing coin denominations and a total amount of money. Return the fewest number of coins needed to make up that amount. If the amount cannot be made up by any combination of the coins, return -1.

Example 1
  • Input: coins = [1, 2, 5], amount = 11
  • Output: 3
  • Explanation: 11 = 5 + 5 + 1, so you need at least 3 coins.
Example 2
  • Input: coins = [2], amount = 3
  • Output: -1
  • Explanation: There's no way to make the amount 3 using only coins of denomination 2.
Constraints
  • 1 ≤ coins.length ≤ 12
  • 1 ≤ coins[i] ≤ 2^31 - 1
  • 0 ≤ amount ≤ 10^4
  • Time Complexity: O(amount * coins.length)
  • Space Complexity: O(amount)
ArraysDynamic Programming Tech MahindraeBay
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming to solve this problem
  • Create a dp array to store the minimum number of coins needed for each amount
  • Initialize the dp array with amount + 1 (a value larger than any possible answer)
  • Set dp[0] = 0 since no coins are needed to make amount 0
  • For each coin and each possible amount, update dp[amount] if using the current coin results in fewer total coins

Steps to solve by this approach:

 Step 1: Create a dp array of size amount + 1 to store the minimum number of coins needed for each amount.
 Step 2: Initialize dp[0] = 0 (base case - no coins needed for amount 0) and dp[1...amount] = amount + 1 (a value larger than any possible answer).
 Step 3: For each coin denomination, iterate through all possible amounts from the coin value to the target amount.
 Step 4: For each amount j, update dp[j] = min(dp[j], dp[j - coins[i]] + 1), meaning we either don't use the current coin or use it and add 1 to the solution for amount j - coins[i].
 Step 5: After filling the dp array, if dp[amount] is still amount + 1, it means the amount can't be made, so return -1.
 Step 6: Otherwise, return dp[amount] which contains the minimum number of coins needed.
 Step 7: The final answer represents the optimal solution for the coin change problem.

Submitted Code :