Skip to content

Feat: add coin change algorithm #212

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions dynamic_programming/coin_change.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@

export interface CoinChange {
minCoins: number,
coins: number[]
}

/**
* Given a set of categories of coins C and an amount of money S, the goal is:
* to give change for S but to use a minimum number of coins. Suppose each category of coin has an infinite number of pieces.
* @param money - amon of money.
* @param coins - The coins that are available.
* @returns CoinChange, the minimum number of coins, and which coins are selected
*/
export const coinChange = (money: number, coins: number[]): CoinChange => {

const minCoins: number[] = Array(money + 1).fill(Infinity);
const lastCoin: number[] = Array(money + 1).fill(-1);

minCoins[0] = 0;

// Fill in the DP table
for (let i = 0; i < coins.length; i++) {
for (let j = 0; j <= money; j++) {
if (j >= coins[i]) {
if (minCoins[j] > 1 + minCoins[j - coins[i]]) {
minCoins[j] = 1 + minCoins[j - coins[i]];
lastCoin[j] = coins[i];
}
}
}
}

const res: CoinChange = {
minCoins: minCoins[money],
coins: []
}

let total: number = money;
while (total > 0) {
res.coins.push(lastCoin[total]);
total -= lastCoin[total];
}

return res;
}

37 changes: 37 additions & 0 deletions dynamic_programming/test/coin_change.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { CoinChange, coinChange } from "../coin_change";


interface TestCase {
money: number,
coins: number[],
expected: CoinChange
}

const cases: TestCase[] = [
{
money: 13,
coins: [7, 2, 3, 6],
expected: {
minCoins: 2,
coins: [6, 7]
}
},
{
money: 10,
coins: [1, 5],
expected: {
minCoins: 2,
coins: [5, 5]
}
}
];

describe("Coin Change Algorithm Test", () => {
test.each(cases)(
"given money: $money, and coins: $coins the minimum coin change should return $expected",
({money, coins, expected}) => {
const result = coinChange(money, coins);
expect(result).toEqual(expected);
}
);
});