Code did not passed in all test cases , pls help

import java.util.*;
class Solution
{
public List findMajority(int arr[] , int n)
{
List ans = new ArrayList();
int ele1 = 0 , count1 = 0 , ele2 = 0 , count2 = 0 ;
for(int i = 0 ; i < arr.length ; i++)
{
if(arr[i] == ele1)
{
count1++;
}
else if(arr[i] == ele2)
{
count2++;
}
else if(count1 == 0)
{
ele1 = arr[i];
count1 = 1;
}
else if(count2 == 0)
{
ele2 = arr[i];
count2 = 1;
}
else
{
count1–;
count2–;
}
}
for( int i = 0 ; i < n ; i++)
{
if(ele1 == arr[i])
{
count1++;
}
else if(ele2 == arr[i])
{
count2++;
}
}
if(count1 >= (n/3))
{
ans.add(ele1);
}
if(count2 >= (n/3));
{
ans.add(ele2);
}
return ans;
}

}
public class Main {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
int total = in.nextInt();
int arr[] = new int[total];
for(int i = 0 ; i < total ; i++)
{
arr[i] = in.nextInt();
}
Solution obj = new Solution();
List result = obj.findMajority(arr,total);
for(int x : result)
{
System.out.print(x + " ");
}
}
}

Hey @priyanshudhar4 The code you have sent is quite unreadable can you please add you code in ide.codingblocks and then send me the link to the code?

hey @priyanshudhar4Your logic is only for 2 elements if there are two majority elements. First try this question in O(N^2) then try to optimise it.

Could you please help how to solve this problem

Hey @priyanshudhar4 The hint is first try to sort the array and then find the element.

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.