I wrote a code that finds the longest continuum in the array that the sum of the values in the continuum equal to zero modulo 3, e.g for the array a[]={2,-3,5,7,-20,7}
We have 2-3+5+7-20=-9 so the output is 5, My problem is the complexity, now it's O(n^3)
a bird whispered me that it can be done in O(n)
public class mmn {
public static void main(String[] args)
{
int a[]={2,-3,5,7,-20,7};
int r=what(a);
System.out.println(r);
}
private static int f(int[]a,int low, int high)
{
int res=0;
for (int i=low;i<=high;i++)
res+=a[i];
return res;
}
public static int what(int[]a)
{
int temp=0;
for(int i=0;i<a.length;i++)
{
for (int j=i;j<a.length;j++)
{
int c=f(a,i,j);
if (c%3==0)
{
if(j-i+1>temp)
temp=j-i+1;
}
}
}
return temp;
}
}
Attempt to rewrite in O(n):
import java.util.*;
class Main {
public static void main (String[] args) throws Exception {
// you should use only one Scanner object
Scanner scanner = new Scanner(System.in);
int a[]={3,1,3,1,3,1};
int n=a.length;
int S[]=new int[n];
int i[]=new int[n];
int best;
int sum;
for (int j=0; j<n; j++) {
S[j]=a[j]%3;
i[j]=j;// initialize
//System.out.println(S[j]);
//System.out.println(i[j]);
}
best=1;
for (int k=1; k<n; k++) {
if((S[k-1]+S[k])%3==0) {//checking if we want a longer continuum
S[k]=S[k-1]+a[k];
i[k]=i[k-1];
}
if(S[k]<S[best])//check if i should update the better
best=k-1;
}
System.out.println(best);
}
}