Rod Cutting
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)
Solution
// recursive
function cuttingRod(n, prices){
// handle size n
if (n==0) return 0
// define max var
let max = -Infinity
let i=0
while(i<n){
let tmp = prices[n-i-1]+cuttingRod(i, prices)
if(tmp>max) max=tmp
i++
}
return max
}
// dp
function cuttingRodsDP(n, prices){
let arr = new Array(n+1)
arr[0]=0
for(let i=1;i<=n;i++){
let maxVal = -1
for(let j=1;j<=i;j++){
let temp = prices[j-1]+arr[i-j]
if(temp>maxVal) maxVal=temp
}
arr[i]=maxVal
}
return arr[n]
}
const prices = [3,5,8,9,10,20,22,25]
const n = 5
cuttingRods(n, prices) // 15
comments powered by Disqus