
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.
- We need to make amount 6 using coins [1,3,4].
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.
- We need to make amount 3 using coins [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)
Editorial
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. |
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