Computing and improving the complexity of time and memory (Java)

private static int Sum (int[] a, int from, int to){
    int total=0;
    for (int i=from; i <= to; i++)
        res += a[i];
    return total;
}

public static int Method3 (int []a){
    int temp=0;
    for (int i=0; i <= a.length; i++)
    {
        for (int j=0; j <= a.length; j++)
        {
            int c = Sum(a,i,j);
            if (c%3 == 0)
            {
                if (j-i+1 > temp)
                temp = j-i+1;
             }
         }
    }
    return temp;
}

The purpose of Method3 is to find the longest combination of given array numbers', so that the sum of the numbers in the combination can be divided by 3 without a remainder. Now I'm trying to find out the complexity of the time and memory of Method3, and then my goal is to learn how to improve it as much as possible.

:   3 O (n ^ 2), (n + (n-1) +... +1) , [n (n + 1)]/2 = > (1/2) n ^ 2 + (1/2) n = > O ( ^ 2). , Sum, Method3, O (n) - j ( a.length ) , 3: n ^ 2 * n = n ^ 3. ? , , . , O (1), , .

, ? - ? , , , , , ?

!

+4
1

, - O (n ^ 3). , - O (1). - .

, . j. , 1, 2, 3, 4. 1-2, 1-3, 1-4, 2-3, 2-4, 3-4.

j = a.length() - 1. , " " i. ( , Sum (1, i, j)% 3 == 0), j, .

Sum , .

EDIT:

- O (n ^ 3). , ? , ) , N ^ 3.

0

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


All Articles