I looked at CLRS the other day to refresh my thoughts a bit and ran into the problem of classic cutting of rods.
The classic bottom-up solution for this is this:
1: let r[0..n] be a new array 2: r[0] = 0 3: for j = 1 to n 4: q = -1 5: for i = 1 to j 6: q = max(q, p[i] + r[ji]) 7: r[j] = q 8: return r[n]
Now I'm thinking about something. Why do we keep using p [i] on L.6? I mean, let's say that we have j = 4, then he calculated the following combinations:
1 + 3 2 + 2 3 + 1 4 + 0
what is the calculation point "3 + 1" twice. I suggest not using p [] and using r [] and stopping on the floor (j / 2).
1: let r[0..n] be a new array 2: r[0] = 0 3: for j = 1 to n 4: q = p[j] 5: for i = 1 to floor(j/2) 6: q = max(q, r[i] + r[ji]) 7: r[j] = q 8: return r[n]
Does anyone see something wrong with this approach?
Thanks,
source share