Tutorialspoint
Problem
Solution
Submissions

Coin Change

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

Write a JavaScript program to find the minimum number of coins needed to make up a given amount. You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. 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:
    • We need to make amount 6 using coins [1,3,4].
    • One way is to use 1+1+1+1+1+1 = 6 coins (6 coins of value 1).
    • Another way is to use 3+3 = 6 (2 coins of value 3).
    • The minimum number of coins needed is 2.
Example 2
  • Input: coins = [2], amount = 3
  • Output: -1
  • Explanation:
    • We need to make amount 3 using coins [2].
    • We cannot make amount 3 using only coins of value 2.
    • No combination of coins can sum to 3.
    • Therefore, we return -1 to indicate it's impossible.
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)
Dynamic Programming HCL TechnologiesZomato
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 optimization problem
  • Create a DP array where dp[i] represents minimum coins needed for amount i
  • Initialize dp[0] = 0 (zero coins needed for amount 0)
  • For each amount, try using each coin and take the minimum
  • If amount cannot be made, dp[amount] will remain infinity

Steps to solve by this approach:

 Step 1: Create a DP array of size (amount + 1) and initialize all values to infinity except dp[0] = 0.

 Step 2: The dp[i] represents the minimum number of coins needed to make amount i.
 Step 3: Iterate through each amount from 1 to the target amount.
 Step 4: For each amount, try using each available coin denomination.
 Step 5: If a coin value is less than or equal to current amount, update dp[i] with the minimum of current value and dp[i - coin] + 1.
 Step 6: After processing all amounts, check if dp[amount] is still infinity.
 Step 7: Return dp[amount] if it's possible to make the amount, otherwise return -1.

Submitted Code :