0
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.

0

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Here n = q-p

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.