简体   繁体   中英

Complexity of an Nested Loop (Recurrence Relation)

Algorithm-1 (A:array[p..q] of integer)
    sum, max: integer
    sum = max = 0
    for i = p to q 
        sum = 0
        for j = i to q 
            sum = sum + A[j]
            if sum > max then
                max = sum
    return max

How many times does the nested loop execute?

I'm aware that the first for loop has an O(n) complexity, and that the whole algorithm has a total complexity of O(n^2) . However, I need the exact number of executions of the inner loop in order to prove this via a recurrence relation.

Probably not the answer you were looking for. In fact, you got it right that the inner loop has O(n) and the entire program has O(n^2) complexity. Just throw in a counter and increment it in your inner loop. That should give you the exact number of executions.

If you want an exact number, the inner loop is invoked (n + n-1+ ...1) = n(n+1)/2 ~= O(n^2)

Here n = qp

Wouldn't it just be Sum(i = 1 -> n, i) , which equals n(n+1)/2 ?

In your case, n = q-p+1 , so you get (q-p+1)(q-p+2)/2 .

Expanding this out - if I've done this right - you get (q^2-qp+2q-pq+p^2-2p+q-p+2)/2 = (q^2+p^2-2qp+3q-3p+2)/2 .

The inner loop runs q-i+1 times and the total number of executions is

\\sum{ i=p }^{ q } (q-i+1) = \\sum{ k=1 }^{ q-p+1 } (k) = n * (n+1) /2

where n = q-p+1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM