Rob Levin
1 min readJan 2, 2020

--

Hi Ranjitha, thanks for taking the time to make this post! I found it quite useful as I think best in JavaScript and happened to be working on Coin Change (min variant)! I tinkered a bit and came up with very similar code but:

var coinChange = function(coins, amount) {
if (amount === 0) return 0
const grid = []

for (let row = 0; row <= coins.length; row++) {
grid[row] = []
for (let col = 0; col <= amount; col++) {
// Prefill zero'th columns with zero, and first row with Infinity
if (col === 0) {
grid[row][col] = 0
continue
} else if (row === 0) {
grid[row][col] = Infinity
continue
}
// Tabulation--as we're not on first column or row
const currCoin = coins[row-1]
// Current coin larger then column, just pull down last value
if (currCoin > col) {
grid[row][col] = grid[row-1][col]
} else {
// Minimum of pulled down last value vs. including coin (1) + previous solution at [col - coin]
grid[row][col] = Math.min(grid[row-1][col], 1 + grid[row][col - currCoin])
}
}
}
return grid[coins.length][amount] == Infinity ? -1 : grid[coins.length][amount]
};

After having watched a bunch of tabulation youtubes I wanted to make it crystal clear to myself on the meaty part of the solution where we indice based off [current index less the current coin]. Nothing meaningfully different then yours, but I thought you’d like to see that your post inspired some study :) Thanks Ranjitha!

--

--

No responses yet