Maximum Consecutive Ones
Problem
The array has only 0 and 1. Print the length of the longest run of 1s that follow each other.
Constraints
- 1 <= n <= 10^5
- a[i] is 0 or 1
Examples
Input
6 1 1 0 1 1 1
Output
3
Solutions
A common bug is to count all pairs of neighbouring ones in the whole array. The correct method resets the counter at every 0 and remembers the best run.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The longest run of ones.
* Approach: Reset on a zero.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(int[] a) {
// Step 1: current = the length of the run of ones that ends here. best = the longest run so far.
int current = 0;
int best = 0;
for (int value : a) {
// Step 2: A 1 extends the run. A 0 ends the run, so we start again at 0.
if (value == 1) {
current++;
} else {
current = 0;
}
// Step 3: Keep the longest run.
best = Math.max(best, current);
}
return best;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- What must happen to the counter at a 0?