Skip to content

Commit bec49ca

Browse files
Create CoinChangeI.java
1 parent 644071d commit bec49ca

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 CoinChangeI { // Coin Change I
2+
public int coinChange(int[] coins, int amount) {
3+
int n = coins.length;
4+
5+
int[][] dp = new int[n][amount+1];
6+
7+
// for(int i = 0; i<n; i++){
8+
// dp[i][0] = 0;
9+
// }
10+
11+
for(int j = 0; j<amount+1; j++){
12+
if(j % coins[0] == 0){
13+
dp[0][j] = j/coins[0];
14+
}
15+
else{
16+
dp[0][j] = (int)1e9;;
17+
}
18+
}
19+
20+
for(int i = 1; i<n; i++){
21+
for(int j = 0; j<amount+1; j++){
22+
int notPick = dp[i-1][j];
23+
int pick = 0;
24+
if(coins[i]<=j){
25+
pick = 1+dp[i][j-coins[i]];
26+
}
27+
else{
28+
pick = (int)1e9;
29+
}
30+
dp[i][j] = Math.min(notPick, pick);
31+
}
32+
}
33+
34+
return dp[n-1][amount] >= 1e9 ? -1 : dp[n-1][amount];
35+
}
36+
}

0 commit comments

Comments
 (0)