Skip to content
Prev Previous commit
Add input validation to coin change algorithms
  • Loading branch information
MayankSharma-2812 committed Jan 30, 2026
commit ff5be5bb05c9ebed04993ea7b038923cdc01beff
44 changes: 39 additions & 5 deletions Dynamic-Programming/CoinChange.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,57 @@
* @params {Number} amount
*/
export const change = (coins, amount) => {
// Create and initialize the storage
if (!Array.isArray(coins)) {
throw new TypeError('Coins must be an array')
}

if (typeof amount !== 'number' || amount < 0) {
throw new TypeError('Amount must be a non-negative number')
}

if (amount === 0) {
return 1
}

if (coins.length === 0) {
return 0
}

const combinations = new Array(amount + 1).fill(0)
combinations[0] = 1
// Determine the direction of smallest sub-problem

for (let i = 0; i < coins.length; i++) {
// Travel and fill the combinations array
for (let j = coins[i]; j < combinations.length; j++) {
combinations[j] += combinations[j - coins[i]]
}
}

return combinations[amount]
}

/**
* @params {Array} coins
* @params {Number} amount
*/
export const coinChangeMin = (coins, amount) => {
const map = { 0: 1 }
if (!Array.isArray(coins)) {
throw new TypeError('Coins must be an array')
}

if (typeof amount !== 'number' || amount < 0) {
throw new TypeError('Amount must be a non-negative number')
}

if (amount === 0) {
return 0
}

if (coins.length === 0) {
return -1
}

const map = { 0: 0 }

for (let i = 1; i <= amount; i++) {
let min = Infinity
for (const coin of coins) {
Expand All @@ -29,5 +62,6 @@ export const coinChangeMin = (coins, amount) => {
}
map[i] = min
}
return map[amount] === Infinity ? -1 : map[amount] - 1

return map[amount] === Infinity ? -1 : map[amount]
}