Skip to content

Commit 1d138c0

Browse files
Jeehay28Jeehay28
Jeehay28
authored and
Jeehay28
committed
Add coin-change solution in TypeScript
1 parent a507584 commit 1d138c0

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

coin-change/Jeehay28.ts

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// Approach 2: Dynamic Programming
2+
// // Time Complexity: O(amout * n), where n is the number of coins
3+
// // Space Complexity: O(amount)
4+
5+
function coinChange(coins: number[], amount: number): number {
6+
7+
// input: coins = [2, 3, 5], amount = 7
8+
9+
// initial state dp
10+
// 0: 0
11+
// 1: amount + 1 = 8
12+
// 2: 8
13+
// 3: 8
14+
// 4: 8
15+
// 5: 8
16+
// 6: 8
17+
// 7: 8
18+
19+
// using coin 2
20+
// 0: 0
21+
// 1: 8
22+
// 2: 8 -> 8 vs dp[2-2] + 1 = 1 -> 1
23+
// 3: 8 -> 8 vs dp[3-2] + 1 = 9 -> 8
24+
// 4: 8 -> 8 vs dp[4-2] + 1 = 2 -> 2
25+
// 5: 8 -> 8 vs dp[5-2] + 1 = 9 -> 8
26+
// 6: 8 -> 8 vs dp[6-2] + 1 = 3 -> 3
27+
// 7: 8 -> 8 vs dp[7-2] + 1 = 9 -> 8
28+
29+
const dp = Array.from({ length: amount + 1 }, () => amount + 1);
30+
dp[0] = 0
31+
32+
for (const coin of coins) {
33+
for (let currentTotal = coin; currentTotal <= amount; currentTotal++) {
34+
dp[currentTotal] = Math.min(dp[currentTotal - coin] + 1, dp[currentTotal])
35+
}
36+
}
37+
38+
return dp[amount] > amount ? -1 : dp[amount]
39+
};
40+
41+
42+
// // Approach 1: BFS Traversal
43+
// // Time Complexity: O(amout * n), where n is the number of coins
44+
// // Space Complexity: O(amount)
45+
46+
// function coinChange(coins: number[], amount: number): number {
47+
// // queue: [[number of coints, current total]]
48+
// let queue = [[0, 0]];
49+
// let visited = new Set();
50+
51+
// while (queue.length > 0) {
52+
// const [cnt, total] = queue.shift()!;
53+
54+
// if (total === amount) {
55+
// return cnt;
56+
// }
57+
58+
// if (visited.has(total)) {
59+
// continue;
60+
// }
61+
// visited.add(total);
62+
63+
// for (const coin of coins) {
64+
// if (total + coin <= amount) {
65+
// queue.push([cnt + 1, total + coin]);
66+
// }
67+
// }
68+
// }
69+
70+
// return -1;
71+
// }
72+

0 commit comments

Comments
 (0)