Search⌘ K
AI Features

Solution Review: Create an Amount

Understand the fundamentals of solving the coin amount problem using recursion and dynamic programming in JavaScript. Learn how to apply base cases, reduce problem size recursively, and optimize with memoization to enhance efficiency. This lesson strengthens your problem-solving skills for interview challenges involving recursion and dynamic programming.

Solution: recursive #

Let’s start by discussing the recursive solution to this problem.

Javascript (babel-node)
function returnWays(coins, numOfCoins,amount) {
if(amount === 0) return 1; // only one way to return zero amount
if(amount < 0) return 0; // No solution exists for negative amount
if(numOfCoins < 0 && amount > 0) return 0; // If no coins left
return returnWays(coins, numOfCoins, amount - coins[numOfCoins]) +
returnWays(coins, numOfCoins - 1, amount);
}
var coins = [1, 2, 3];
var amount = 4;
console.log(returnWays(coins,coins.length-1,amount));

Explanation #

We start with a big problem. Given an amount and an array of coins, we have to find the number of ways to return that amount using the coins from the array.

In a recursive solution, we split the ...