-1

I was wondering what the loop invariant would be for the loop present in lines 4 - 6 of this code and how to prove it during intialization, mantience, and termination.

def cut_rod(p, n):
    if n == 0:
        return 0
    q = -inf
    for i = 1 to n:
        q = max(q, p[i] + cut_rod(p, n-i))
    return q

I wasn't really sure where to start here so some insight would be great :)

2 Answers2

0

I would say that after each iteration q = min price of rod with len n cut containing at least 1 piece of len <= i.

This can be proven inductively.

Dimitrius
  • 564
  • 6
  • 21
0

with the q = -inf initialisation you're guaranteed to return the max of q and the recursion of this function

Amy
  • 59
  • 6