Skip to content

Commit f9efe99

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent f9e8d55 commit f9efe99

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
// Function to solve the coin change problem using bottom-up dynamic programming
4+
int solve(vector<int>& coins, int x) {
5+
// Create a dp array where dp[i] represents the minimum number of coins needed to make up amount i
6+
vector<int> dp(x + 1, INT_MAX);
7+
8+
// Base case: 0 coins are needed to make up amount 0
9+
dp[0] = 0;
10+
11+
// Iterate over each amount from 1 to x
12+
for(int i = 1; i <= x; i++) {
13+
// Check each coin to see if it can contribute to the current amount
14+
for(int j = 0; j < coins.size(); j++) {
15+
// If the current coin can be used (i - coins[j] >= 0)
16+
// and the subproblem dp[i - coins[j]] has a valid solution (not INT_MAX)
17+
if(i - coins[j] >= 0 && dp[i - coins[j]] != INT_MAX) {
18+
// Update dp[i] to the minimum of its current value and the result of using this coin
19+
dp[i] = min(dp[i], 1 + dp[i - coins[j]]);
20+
}
21+
}
22+
}
23+
24+
// If the amount x cannot be formed with the given coins, return -1
25+
if(dp[x] == INT_MAX) return -1;
26+
27+
// Otherwise, return the minimum number of coins needed to make up amount x
28+
return dp[x];
29+
}
30+
31+
// Main function to find the minimum number of coins to make up the given amount
32+
int coinChange(vector<int>& coins, int amount) {
33+
// Use the bottom-up approach to solve the problem
34+
return solve(coins, amount);
35+
}
36+
};

0 commit comments

Comments
 (0)