Big O runtime for this algorithm?

Here's the pseudo code:

Baz(A) {
    big = −∞
    for i = 1 to length(A)
        for j = 1 to length(A) - i + 1
            sum = 0
            for k = j to j + i - 1
                sum = sum + A(k)
            if sum > big
                big = sum
    return big

So, line 3 will be O (n) (n is the length of the array, A) I'm not sure which line will be ... I know that it decreases by 1 every time it starts, because I will increase. and I cannot get row 6 without getting row 4 ...

All help is appreciated, thanks in advance.

+4
source share
3 answers

Let's first understand how the first two cycles work.

for i = 1 to length(A)
        for j = 1 to length(A) - i + 1

1 n ( A), i. SO, = 1 n . 2, (n-1) .., 1.

, :

n + (n - 1) + (n - 2) + (n - 3) + .... + 1 times...

: sum ( 1 n) = N * (N + 1) / 2, (N^2 + N)/2 , Big oh

O (n ^ 2) (Big Oh of n square)

...

:

for k = j to j + i - 1

for k = 0 to i - 1 ( , / j, , , , )

, 0 1 ( i) n , 0 2 ( i) (n - 1) .

, :

n + 2(n-1) + 3(n-2) + 4(n-3)..... 

= n + 2n - 2 + 3n - 6 + 4n - 12 + ....

= n(1 + 2 + 3 + 4....) - (addition of some numbers but this can not be greater than n^2)

= `N(N(N+1)/2)`

= O(N^3)

, N ^ 3 (Big Oh of n cube)

, !

+4

, Sigma Notation:

enter image description here

+1
Baz(A):
    big = −∞
    for i = 1 to length(A)
        for j = 1 to length(A) - i + 1
            sum = 0
            for k = j to j + i - 1
                sum = sum + A(k)
            if sum > big
                big = sum
    return big

Big-O

Big-O - ,

, ,

for i = 1 to length(A)
    for j = 1 to length(A) - i + 1
        for k = j to j + i - 1
            sum = sum + A(k)

,

SUM { SUM { i } for j = 1 to n-i+1 } for i = 1 to n

= 1/6 n (n+1) (n+2)

= (1/6 n^2 + 1/6 n) (n + 2) 

= 1/6 n^3 + 2/6 2 n^2 + 1/6 n^2 + 2/6 n

= 1/6 n^3 + 3/6 2 n^2 + 2/6 n

= 1/6 n^3 + 1/2 2 n^2 + 1/3 n

T(n) ~ O(n^3)
0

Source: https://habr.com/ru/post/1536694/


All Articles