Reputation: 5243
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.
Upvotes: 0
Views: 1543
Reputation: 959
array[i] = max(array[i],prices[j]+array[i-j])
looks right to me.
In that algorithm, j
represents the length of rod of your initial cut. We start off with a rod of length i
and cut off j
. Then, we need to know how much we can get for a rod of i - j
because you just cut off j
length and you're left with i - j
. But we know this value is at least as high as price[i-j]
because we have the option of selling the rod as a whole or by cutting it to increase its value.
Example: We have a rod of length 4. Assuming array[] already contains optimal values for 1,2,3, then we:
cut off a piece of length 1, then check how much we can get for a rod of length 3
cut off a piece of length 2, then check how much we can get for a rod of length 2
cut off a piece of length 3, then check how much we can get for a rod of length 1
And pick the maximum.
If we used array[i] = max(array[i],array[j]+array[i-j])
array[k]
contains the maximum value for a rod of length k if we cut it into pieces. So these values would be unexpectedly high compared to if we used price[k]
.
Also the current step in the recursion only cares about making one cut, and checking the leftover's max value, not both sides max values (that will be taken care of when you find that the value of a large cut may not be ideal)
Upvotes: 1