Max Consecutive Ones
Find the length of the longest consecutive run of ones in a binary array.
Work through the cases
3 examplesInput notation
A nonempty line containing only 0 and 1, separated by spaces.Expected result
The maximum run length.Case 1
Input
1 1 0 1 1 1
Expected output
3
Case 2
Input
0 0
Expected output
0
Case 3
Input
1
Expected output
1
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Longest run of ones. Checking every subarray is O(n^2); one scan is enough. A 1 grows the current run and updates the answer; a 0 resets the counter. Zeros separate runs, so the counter never joins two blocks.
We can iterate through the array, using a variable cnt to record the current number of consecutive 1s, and another variable ans to record the maximum number of consecutive 1s.
When we encounter a 1, we increment cnt by one, and then update ans to be the maximum of cnt and ans itself, i.e., ans = \max(ans, cnt). Otherwise, we reset cnt to 0.
After the iteration ends, we return the value of ans.
The time complexity is O(n), where n is the length of the array. The space complexity is O(1).
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int ans = 0, cnt = 0;
for (int x : nums) {
if (x == 1) {
ans = Math.max(ans, ++cnt);
} else {
cnt = 0;
}
}
return ans;
}
}Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.
Solutions adapted from Doocs / LeetCode contributors, licensed under CC BY-SA 4.0. Formatting changed; TypeScript versions converted to JavaScript. Supplemental implementations and approach notes added. Adapted solution material is available under the same license.