If you want to find the maximum sub array length which contains only continious r
and b
, here is a solution. The basic idea is using two cursor and greedy search.
public static int findMaximum(char[] input) {
int result = 0;
int first = 0;
int second = 0;
while (input[first] == input[second]) {
second++; // the second index should start from another character
}
while (second < input.length) {
int preSecond = second; // copy second, in need reset first to it
while (second + 1 < input.length && input[second] == input[second + 1]) {
second++; // increment second
}
result = Math.max(result, second - first + 1);
if (second < input.length - 1) {
first = preSecond;
}
second++;
}
return result;
}
some test cases:
public static void main(String[] args) {
System.out.println(findMaximum(new char[]{'b','b','r'})); //3
System.out.println(findMaximum(new char[]{'b','b','r','r'})); //4
System.out.println(findMaximum(new char[]{'b','b','r','r','r','b','r'})); //5
System.out.println(findMaximum(new char[]{'b','b','b','r','r','b','r'})); //5
System.out.println(findMaximum(new char[]{'b','b','r','r','b','r','r','r','r','r'})); //6
}
1
solved How do I count the maximum number of two characters in a array?