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

前端 未结 9 1022
傲寒
傲寒 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:21

    This requires O(n^3) time due to the fact that in the three loops, three distinct variables are incremented. That is, when one inside loop is over, it does not affect the outer loop. The outer loop runs as many times it was to run before the inner loop was entered.

    And this is the maximum contiguous subarray sum problem. Self-explanatory when you see the example:

    {99, 1} => returns 100
    {-1, -2, -3} => return -1
    {-1, 5, -2} => returns 5
    {99, -3, 0, 1} => returns 99
    

    There is an excellent algorithm known as Kadane's algorithm (do google for it) which solves this in O(n) time.

    Here it goes:

    Initialize:
        max_so_far = 0
        max_ending_here = 0
    
    Loop for each element of the array
      (a) max_ending_here = max_ending_here + a[i]
      (b) if(max_ending_here < 0)
                max_ending_here = 0
      (c) if(max_so_far < max_ending_here)
                max_so_far = max_ending_here
    return max_so_far
    

    References: 1, 2, 3.

提交回复
热议问题