-6

In Java, given the array A[a,a,b,b,b,c,d,e,e] return 'b' because it appears consecutively more than any other element in the array. I have tried comparing each element with the next and if they match, incrementing a count and then returning the element with the highest count but I don't know how to implement it into code.

JoeSmith
  • 3
  • 1

2 Answers2

2

Note - This assumes the characters are in BMP

  1. Maintain 4 states - prev character, current character, current count, max count
  2. Initial prev character to some invalid character or empty
  3. initialize count to zero
  4. Iterate over characters and if at any time current character and previous character mismatch, then reset current character and current count
  5. When ever current count is greater than max count, then update current character as max character and update max count
    public static void main(String[] args) {
        char[] input = new char[] {'a', 'b', 'b', 'b', 'b', 'c', 'd', 'e', 'e'};
        if (input.length == 0) {
            return;
        }
        char prev = (char) (input[0] - 1); // choose a character other than first character
        char maxChar = prev;
        int maxCount = 0;
        int currentCount = 0;
        for (final char current : input) {
            if (prev != current) {
                prev = current;
                currentCount = 0;
            }
            currentCount++;
            if (currentCount > maxCount) {
                maxCount = currentCount;
                maxChar = current;
            }
        }
        System.out.println(maxChar);
    }
Thiyanesh
  • 2,360
  • 1
  • 4
  • 11
0

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
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42