I am trying to solve the standard rod-cutting problem through dynamic programming. As found here and here, the recurrence relations seems to be:
prices = [1..n]
array[1..n]
array[1] = prices[1]
for i in (2..n)
{
array[i] = INT_MIN
for j in (1..i-1)
{
array[i] = max(array[i],prices[j]+array[i-j])
}
}
And array[n]
returns the value for n
, which is our answer. My question lies in the line
array[i] = max(array[i],prices[j]+array[i-j])
Shouldn't it be
array[i] = max(array[i],array[j]+array[i-j])
Imagine we are trying to find max value for length 8
. Now, for 4
we find that the value we obtain by cutting one single unit of length 4
is less than say obtained by cutting lengths of 3
and 1
, i.e for n = 4
, prices[4]
is not optimal. But since we are building the result array bottom up, array[4]
is optimal. So won't array[4]+array[4]
be the max value for n = 8
, compared to prices[4]+array[4]
? My resulting solution looks something like this:
prices = [1..n]
array[1..n]
for i in (1..n)
array[i] = prices[i] //prices[i] is the minimum value we can obtain by cutting it fully
for i in (2..n)
{
for j in (1..i-1)
{
array[i] = max(array[i],array[j]+array[i-j]) // find out all possible (j,i-j) pairs, and compare with array[i]
}
}
If this is not correct, please tell me where am I erring logically.