简体   繁体   中英

Inner for loop time complexity

int value2= 0;
int value1=0;
for (int i = 0; i < A.size(); i++)
    for (int j = i; j < A.size(); j++) {
        value2 = 0;
        for (int k = i; k <= j; k++)
            value2 += A[k];
        if (value2 > value1)
            value1 = value2;
    }



q=clock()-q;

cout << "Total Time: "<< ((float)q)/CLOCKS_PER_SEC <<"\n";
cout <<"Result: " << value1 <<"\n";

I went through and calculated the relational math for these nested loops but I am really confused about what the complexity for the 2nd and 3rd loops would be. My first thought was that the 2nd is n-1 and the third is just n because of the k <= j but I'm not entirely sure.

Big O notation is used to express a "bound". so, call A.size() to n , it can be O(n^3) in Big-O notation.

or more strictly, the first and second loops are O(n^2) because the sum of count is n + (n-1) + ... + (n - (n - 1)) = n*(n+1)/2 . - (a)

the third one gets affected by only i , and j . Let's count how many interval [i, j] is in.

the length of [i, j] can assume to n in Big-O's view. - (b)

therefore (a) * (b) is O( (n*(n+1)/2) * n ) = O(n^3) .


In summary (on the other way), count it all.

there are n intervals which size is 1 as like: [0, 0], [1, 1], ..., [n, n]
there are n-1 intervals which size is 2 as like: [0, 1], [1, 2], ..., [n-1, n]
...
there are only 1 intervals which size is n as like: [n, n] when i=0, j=n-1 .

thus, n*1 + (n-1)*2 + ... + 1*n = (n-1)*n*(n+1) / 6 is for all loop.

The Big-O notation is O(n^3)

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