Skip to content

Commit 848dc5d

Browse files
committed
Coin Change
1 parent 300d1c1 commit 848dc5d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

coin-change/forest000014.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
Time Complexity: O(coins.length * amount)
3+
Space Complexity: O(amount)
4+
5+
1 ~ i-1원까지의 최적해를 알고 있다면, i원의 최적해를 구할 때 coins 배열 iteration으로 구할 수 있음
6+
*/
7+
class Solution {
8+
public int coinChange(int[] coins, int amount) {
9+
int c = coins.length;
10+
11+
int[] dp = new int[amount + 1];
12+
Arrays.fill(dp, 99999);
13+
dp[0] = 0;
14+
15+
for (int i = 1; i <= amount; i++) {
16+
for (int j = 0; j < c; j++) {
17+
if (i - coins[j] < 0) {
18+
continue;
19+
}
20+
if (dp[i - coins[j]] >= 0 && dp[i - coins[j]] + 1 < dp[i]) {
21+
dp[i] = dp[i - coins[j]] + 1;
22+
}
23+
}
24+
}
25+
26+
return dp[amount] == 99999 ? -1 : dp[amount];
27+
}
28+
}

0 commit comments

Comments
 (0)