Created
December 4, 2019 02:29
-
-
Save iamshadmirza/49d12e9d38860666f841d7825b3da161 to your computer and use it in GitHub Desktop.
Optimized recursive solution for cut rod problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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