Tutorialspoint
Problem
Solution
Submissions

Coin Change Problem

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

Write a C program to find the minimum number of coins needed to make a given amount. You are given coins of different denominations and a total amount of money. If that amount of money cannot be made up by any combination of the coins, return -1.

Example 1
  • Input: coins = [1, 3, 4], amount = 6
  • Output: 2
  • Explanation: Step 1: To make amount 6, we can use coins [3, 3]. Step 2: This uses 2 coins, which is the minimum possible. Step 3: Other combinations like [1, 1, 4] use 3 coins, which is more than optimal.
Example 2
  • Input: coins = [2], amount = 3
  • Output: -1
  • Explanation: Step 1: We only have coins of denomination 2. Step 2: It's impossible to make amount 3 using only coins of value 2. Step 3: Therefore, return -1.
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 MicrosoftAccenture
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 optimally.
  • Create a dp array where dp[i] represents minimum coins needed for amount i.
  • Initialize dp[0] = 0 and all other values to a large number (amount + 1).
  • For each amount from 1 to target, try all possible coins.
  • Update dp[amount] = min(dp[amount], dp[amount - coin] + 1).

Steps to solve by this approach:

 Step 1: Create a dp array where dp[i] represents minimum coins needed for amount i.
 Step 2: Initialize dp[0] = 0 and all other values to amount + 1 (impossible value).
 Step 3: For each amount from 1 to target amount, iterate through all available coins.
 Step 4: For each coin, if coin value <= current amount, update dp[amount].
 Step 5: Set dp[amount] = min(dp[amount], dp[amount - coin] + 1).
 Step 6: After processing all amounts, check if dp[amount] is still impossible value.
 Step 7: Return dp[amount] if possible, otherwise return -1.

Submitted Code :