File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Dynamic Programming/2D/Subsequences Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments