Wrong output ( only 3 test cases passed)

Kindly review this code, I reviewed it many times but I can’t catch my mistake!

import java.util.*;
public class Main {

public static ArrayList<Integer> MajorityElements(int[] arr,int n){
    int element1=arr[0], count1=1, element2=0,count2=0;
    for(int i=1;i<n;i++){
        if(arr[i]==element1){
            count1++;
        }
        else if(arr[i]==element2){
            count2++;
        }
        else if(count1==0){
            element1=arr[i];
            count1=1;
        }
        else if(count2==0){
            element2=arr[i];
            count2=1;
        }
        else{
            count1--;
            count2--;
        }
    }
    count1=0;count2=0;
    for(int i=0;i<n;i++){
        if(arr[i]==element1){
            count1++;
        }
        else if(arr[i]==element2){
            count2++;
        }
    }
    ArrayList<Integer> ans = new ArrayList<>();
    if(count1>n/3){
        ans.add(element1);
    }
    if(count2>n/3){
        ans.add(element2);
    }
    return ans;
}

public static void main (String args[]) {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    int[] arr=new int[n];
    for(int i=0;i<n;i++){
        arr[i]=sc.nextInt();
    }
    ArrayList<Integer> ans=MajorityElements(arr,n);
    for(int i:ans){
        System.out.print(i+" ");
    }
}

}

It’s working now https://ide.codingblocks.com/s/574298

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.