Skip to content

Instantly share code, notes, and snippets.

@iamshadmirza
Created December 4, 2019 02:29
Show Gist options
  • Save iamshadmirza/49d12e9d38860666f841d7825b3da161 to your computer and use it in GitHub Desktop.
Save iamshadmirza/49d12e9d38860666f841d7825b3da161 to your computer and use it in GitHub Desktop.
Optimized recursive solution for cut rod problem
function cutRod(n, prices){
if(n === 0){ return 0; }
let maxRevenue = -1;
for( let i = 0; i < n; i++){
maxRevenue = Math.max(maxRevenue, prices[n- i - 1] + memoizedCutRod(i, prices));
}
return maxRevenue;
}
function memoize(fn){
const cache = {};
return function(...args){
if(cache[args[0]]){
return cache[args[0]];
}
const result = fn(args[0], args[1]);
cache[args[0]] = result;
return result;
}
}
const memoizedCutRod = memoize(cutRod);
const n = 8, prices = [1, 5, 8, 9, 10, 17, 17, 20];
console.log(memoizedCutRod(n, prices))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment