Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 leaning towards O(n3).
Can someone tell me what it is and why?

My idea that it's O(n2) is because in the j loop, j = i which gives a triangle shape, and then the k loop goes from i + 1 to j, which I think is the other half of the triangle.

public static int what(int[] arr) {     int m = arr[0];     for (int i=0; i<arr.length; i++)     {         for (int j=i; j<arr.length;j++)         {             int s = arr[i];             for (int k=i+1; k<=j; k++)              s += arr[k];             if (s > m)              m = s;         }     }     return m; } 

Also if you can tell me what it does?

I figured it returns the addition of positive integers or the biggest integer in the array.
But for arrays like {99, -3, 0, 1} it returns 99, which I think is because it's buggy. If not than I have no Idea what it does:

{99, 1} => returns 100 {-1, -2, -3} => return -1 {-1, 5, -2} => returns 5 {99, -3, 0, 1} => returns 99 ??? 
like image 620
Seth Keno Avatar asked Apr 02 '14 07:04

Seth Keno


2 Answers

You can proceed methodically, using Sigma Notation, to obtain the order of growth complexity:

enter image description here

like image 120
Mohamed Ennahdi El Idrissi Avatar answered Oct 05 '22 10:10

Mohamed Ennahdi El Idrissi


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)

like image 38
Silviu Burcea Avatar answered Oct 05 '22 12:10

Silviu Burcea