Skip to content

Instantly share code, notes, and snippets.

@greekykhs
Last active July 17, 2020 16:03
// Function to return the count of maximum
// consecutive 1's in a binary circular array
public static int getMaxLength(int arr[]) {
int n = arr.length;
// Starting index
int start = 0;
//it will contain number of ones from left
//to right till we encounter zero.
int onesFromStart = 0;
while (start < n && arr[start] == 1) {
onesFromStart++;
start++;
}
// Ending index
int end = n - 1;
//it will contain number of ones from right
//to left till we encounter zero.
int onesFromEnd = 0;
while (end >= 0 && arr[end] == 1) {
onesFromEnd++;
end--;
}
// The array contains all 1s
if (start > end)
return n;
//number of ones between start and end
int onesInMid = 0;
int result = 0;
for (int i = start; i <= end; i++) {
if (arr[i] == 1) {
onesInMid++;
result = Math.max(result, onesInMid);
} else
onesInMid = 0;
}
return Math.max(result, onesFromStart + onesFromEnd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment