diff --git a/dynamic_programming/coin_change.ts b/dynamic_programming/coin_change.ts new file mode 100644 index 00000000..ea18696d --- /dev/null +++ b/dynamic_programming/coin_change.ts @@ -0,0 +1,22 @@ +/** + * Calculates the number of ways to make a target amount using given coin denominations. + * + * @param coins - An array of coin denominations. + * @param numberOfWays - The number of ways to represent the target amount using the given coins. + * @param targetAmount - The target sum to achieve. + * @returns The number of ways to make the target amount with the given coins. + */ +export function coinChange(coins: number[], numberOfWays: number, targetAmount: number): number { + + const dp: number[] = new Array(targetAmount + 1).fill(0); + dp[0] = 1; + + for (let coinIndex = 0; coinIndex < numberOfWays; coinIndex++) { + const coinValue = coins[coinIndex]; + for (let currentAmount = coinValue; currentAmount <= targetAmount; currentAmount++) { + dp[currentAmount] += dp[currentAmount - coinValue]; + } + } + + return dp[targetAmount]; +} diff --git a/dynamic_programming/test/coin_change.test.ts b/dynamic_programming/test/coin_change.test.ts new file mode 100644 index 00000000..dabf3996 --- /dev/null +++ b/dynamic_programming/test/coin_change.test.ts @@ -0,0 +1,43 @@ +import { coinChange } from "../coin_change"; + +describe('Coin Change problem ', () => { + it('should return 0 if there are no coins', () => { + const coins: number[] = []; + const numCoins: number = coins.length; + const targetAmount: number = 5; + const ways = coinChange(coins, numCoins, targetAmount); + expect(ways).toBe(0); + }); + + it('should return 1 when the target amount is 0', () => { + const coins: number[] = [1, 2, 3]; + const numCoins: number = coins.length; + const targetAmount: number = 0; + const ways = coinChange(coins, numCoins, targetAmount); + expect(ways).toBe(1); + }); + + it('should calculate the number of ways correctly', () => { + const coins: number[] = [1, 2, 3]; + const numCoins: number = coins.length; + const targetAmount: number = 5; + const ways = coinChange(coins, numCoins, targetAmount); + expect(ways).toBe(5); + }); + + it('should handle a large target amount', () => { + const coins: number[] = [1, 2, 3]; + const numCoins: number = coins.length; + const targetAmount: number = 1000; + const ways = coinChange(coins, numCoins, targetAmount); + expect(ways).toBeGreaterThan(0); + }); + + it('should handle a large number of coin denominations', () => { + const coins: number[] = new Array(100).fill(1); + const numCoins: number = coins.length; + const targetAmount: number = 5; + const ways = coinChange(coins, numCoins, targetAmount); + expect(ways).toBeGreaterThan(0); + }); +});