LeaderElement - gopichandnishad/Codility GitHub Wiki

public class Solution {

public static void main(String[] args) {
	
	int[] A = {1, 1, 1, 5, 5, 5, 5, 5, 6, 10, 10};
	int result = solution(A);
	
	if (result != -1)
		System.out.println("Leader element is: " + A[result - 1]);
	else 
		System.out.println("There is no Leader element!");
}

private static int solution(int A[]) {
	int count = 1;
	int halfLen = A.length / 2 + 1;
	int prev=A[0];
	for(int i=1;i<A.length;i++)
	{
		if(A[i]==prev)
		{
			count++;
			if(count>=halfLen)
				return count;
		}
		else
		{
			prev=A[i];
			count=1;
		}
	}
	return -1;
}

}