Algorithmic complexity of naive code for processing all consecutive subsequences of a list: n^2 or n^3?

前端 未结 9 1025
傲寒
傲寒 2020-12-25 11:41

I\'m studying for a test and found this question:

I can\'t really determine the complexity, I figured it\'s either O(n2) or O(n3) and I\'m lea

相关标签:
9条回答
  • 2020-12-25 12:22

    You have 3 for statements. For large n, it is quite obvious that is O(n^3). i and j have O(n) each, k is a little shorter, but still O(n).

    The algorithm returns the biggest sum of consecutive terms. That's why for the last one it returns 99, even if you have 0 and 1, you also have -3 that will drop your sum to a maximum 97.

    PS: Triangle shape means 1 + 2 + ... + n = n(n+1) / 2 = O(n^2)

    0 讨论(0)
  • 2020-12-25 12:23

    Code:

    for (int i=0; i<arr.length; i++) // Loop A
    {
        for (int j=i; j<arr.length;j++) // Loop B
        {
            for (int k=i+1; k<=j; k++) // Loop C
            {
                // ..
            }
        }
    }
    

    Asymptotic Analysis on Big-O:

    Loop A: Time = 1 + 1 + 1 + .. 1 (n times) = n
    
    Loop B+C: Time = 1 + 2 + 3 + .. + m = m(m+1)/2
    
    Time = SUM { m(m+1)/2 | m in (n,0] }
    
    Time < n * (n(n+1)/2) = 1/2 n^2 * (n+1) = 1/2 n^3 + 1/2 n^2
    
    Time ~ O(n^3)
    
    0 讨论(0)
  • 2020-12-25 12:26

    O(n^3).

    You have calculated any two item between arr[0] and arr[arr.length - 1], running by "i" and "j", which means C(n,2), that is n*(n + 1)/2 times calculation.

    And the average step between each calculation running by "k" is (0 + arr.length)/2, so the total calculation times is C(n, 2) * arr.length / 2 = n * n *(n + 1) / 4, that is O(n^3).

    0 讨论(0)
提交回复
热议问题