Hi,
I have written the complete code but some of mine test cases are failing. Not able to find the reason. Kindly help.
import java.util.;
import java.lang.;
public class Main {
public static void main (String args[]) {
Scanner sc=new Scanner(System.in);
int n1=sc.nextInt();
int arr[]=new int[n1];
if(n1<=0 ){
System.out.println("No majority elements");
return;}
for(int i=0;i<n1;i++)
arr[i]=sc.nextInt();
int ele1=0,ele2=0,c1=0,c2=0;
for(int n : arr)
{
int ab=Math.abs(n);
if(ele1==ab)
c1++;
else if(ele2==ab)
c2++;
else if(c1==0)
{
ele1=ab;
c1=1;
}
else if(c2==0)
{
ele2=ab;
c2=1;
}
else{
c1--;
c2--;
}
}
int cnt1=0,cnt2=0;
for(int n:arr){
int ab=Math.abs(n);
if(ele1==ab)
cnt1++;
else if(ele2==ab)
cnt2++;
}
ArrayList<Integer> al=new ArrayList<>();
if(cnt1>n1/3)
al.add(ele1);
if(cnt2>n1/3)
al.add(ele2);
if(al.size()==0){
System.out.println("No majority elements");
return;
}
// System.out.print(al);
for(int x:al)
{
System.out.print(x+" ");
}
}
}