Just compare the current element to previous one, count the number of consecutives, and if consecutive element is detected, check if it is more than existing maximum and track the value:
public static int findMostConsecutive(int ... arr) {
int res = arr[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] == arr[i - 1]) {
count++;
if (count > maxCount) {
maxCount = count;
res = arr[i];
}
}
else {
count = 1;
}
}
return res;
}
Tests:
System.out.println("Most consecutive: " + findMostConsecutive(1, 2, 1, 1, 3, 3, 3, 4, 2));
System.out.println("Most consecutive: " + findMostConsecutive(2, 2, 2, 2, 3, 3, 3, 3));
System.out.println("Most consecutive: " + findMostConsecutive(2, 2, 2, 2, 3, 3, 3, 3, 3, 3));
Output
Most consecutive: 3
Most consecutive: 2
Most consecutive: 3
solved Given an array, return the element that occurs the most number of consecutive times. In Java [closed]