Skip to content

Commit 9fe74ce

Browse files
ayoubcappgurueu
andauthored
Feat: add coin change algorithm (#212)
* Feat: add coin change algorithm * Use Infinity rather than just a large number --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
1 parent 7411314 commit 9fe74ce

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

dynamic_programming/coin_change.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
2+
export interface CoinChange {
3+
minCoins: number,
4+
coins: number[]
5+
}
6+
7+
/**
8+
* Given a set of categories of coins C and an amount of money S, the goal is:
9+
* to give change for S but to use a minimum number of coins. Suppose each category of coin has an infinite number of pieces.
10+
* @param money - amon of money.
11+
* @param coins - The coins that are available.
12+
* @returns CoinChange, the minimum number of coins, and which coins are selected
13+
*/
14+
export const coinChange = (money: number, coins: number[]): CoinChange => {
15+
16+
const minCoins: number[] = Array(money + 1).fill(Infinity);
17+
const lastCoin: number[] = Array(money + 1).fill(-1);
18+
19+
minCoins[0] = 0;
20+
21+
// Fill in the DP table
22+
for (let i = 0; i < coins.length; i++) {
23+
for (let j = 0; j <= money; j++) {
24+
if (j >= coins[i]) {
25+
if (minCoins[j] > 1 + minCoins[j - coins[i]]) {
26+
minCoins[j] = 1 + minCoins[j - coins[i]];
27+
lastCoin[j] = coins[i];
28+
}
29+
}
30+
}
31+
}
32+
33+
const res: CoinChange = {
34+
minCoins: minCoins[money],
35+
coins: []
36+
}
37+
38+
let total: number = money;
39+
while (total > 0) {
40+
res.coins.push(lastCoin[total]);
41+
total -= lastCoin[total];
42+
}
43+
44+
return res;
45+
}
46+
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { CoinChange, coinChange } from "../coin_change";
2+
3+
4+
interface TestCase {
5+
money: number,
6+
coins: number[],
7+
expected: CoinChange
8+
}
9+
10+
const cases: TestCase[] = [
11+
{
12+
money: 13,
13+
coins: [7, 2, 3, 6],
14+
expected: {
15+
minCoins: 2,
16+
coins: [6, 7]
17+
}
18+
},
19+
{
20+
money: 10,
21+
coins: [1, 5],
22+
expected: {
23+
minCoins: 2,
24+
coins: [5, 5]
25+
}
26+
}
27+
];
28+
29+
describe("Coin Change Algorithm Test", () => {
30+
test.each(cases)(
31+
"given money: $money, and coins: $coins the minimum coin change should return $expected",
32+
({money, coins, expected}) => {
33+
const result = coinChange(money, coins);
34+
expect(result).toEqual(expected);
35+
}
36+
);
37+
});

0 commit comments

Comments
 (0)