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), , .
, ? - ? , , , , , ?
!
user4282794