Skip to content

Commit 1d417b6

Browse files
committed
feat : coin-change
1 parent 9f5f0a4 commit 1d417b6

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

coin-change/ekgns33.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
input : array of integers each element represents coins, single integer amount
3+
output : fewest number of coin to make up the amount
4+
constraint
5+
1) elements are positive?
6+
yes
7+
2) coins are in integer range?
8+
yes
9+
3) range of amoutn
10+
integer range?
11+
[0, 10^4]
12+
4) at least one valid answer exists?
13+
nope. if there no exist than return -1
14+
15+
edge. case
16+
1) if amount == 0 return 0;
17+
18+
solution 1) top-down approach
19+
20+
amount - each coin
21+
until amount == 0
22+
return min
23+
tc : O(n * k) when n is amount, k is unique coin numbers
24+
sc : O(n) call stack
25+
26+
solution 2) bottom-up
27+
tc : O(n*k)
28+
sc : O(n)
29+
let dp[i] the minimum number of coins to make up amount i
30+
31+
*/
32+
class Solution {
33+
public int coinChange(int[] coins, int amount) {
34+
//edge
35+
if(amount == 0) return 0;
36+
int[] dp = new int[amount+1];
37+
dp[0] = 0;
38+
for(int i = 1; i<= amount; i++) {
39+
dp[i] = amount+1;
40+
for(int coin: coins) {
41+
if(i - coin >= 0) {
42+
dp[i] = Math.min(dp[i], dp[i-coin] + 1);
43+
}
44+
}
45+
}
46+
return dp[amount] == amount+1 ? -1 : dp[amount];
47+
}
48+
}

0 commit comments

Comments
 (0)