Max Consecutive Ones
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given a binary array nums, return the maximum number of consecutive1 ' s in the array.
Examples
Example 1
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Example 2
Input: nums = [1,0,1,1,0,1]
Output: 2
Constraints
1 <= nums.length <= 10^5nums[i]is either0or1.
Solution
Method 1 – Single Pass Linear Scan
Intuition
We want to find the longest sequence of consecutive 1s in the array. By scanning the array once and counting the current streak of 1s, we can keep track of the maximum streak found so far.
Approach
- Initialize two variables:
ansfor the maximum streak andcntfor the current streak. - Iterate through the array:
- If the current element is 1, increment
cntand updateansifcntis greater. - If the current element is 0, reset
cntto 0.
- If the current element is 1, increment
- Return
ansafter the loop.
Code
C++
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int ans = 0, cnt = 0;
for (int x : nums) {
if (x == 1) cnt++;
else cnt = 0;
ans = max(ans, cnt);
}
return ans;
}
};
Go
func findMaxConsecutiveOnes(nums []int) int {
ans, cnt := 0, 0
for _, x := range nums {
if x == 1 {
cnt++
if cnt > ans {
ans = cnt
}
} else {
cnt = 0
}
}
return ans
}
Java
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int ans = 0, cnt = 0;
for (int x : nums) {
if (x == 1) cnt++;
else cnt = 0;
ans = Math.max(ans, cnt);
}
return ans;
}
}
Kotlin
class Solution {
fun findMaxConsecutiveOnes(nums: IntArray): Int {
var ans = 0
var cnt = 0
for (x in nums) {
if (x == 1) cnt++
else cnt = 0
ans = maxOf(ans, cnt)
}
return ans
}
}
Python
class Solution:
def findMaxConsecutiveOnes(self, nums: list[int]) -> int:
ans = cnt = 0
for x in nums:
if x == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans
Rust
impl Solution {
pub fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
let mut ans = 0;
let mut cnt = 0;
for x in nums {
if x == 1 {
cnt += 1;
if cnt > ans {
ans = cnt;
}
} else {
cnt = 0;
}
}
ans
}
}
TypeScript
class Solution {
findMaxConsecutiveOnes(nums: number[]): number {
let ans = 0, cnt = 0;
for (const x of nums) {
if (x === 1) {
cnt++;
ans = Math.max(ans, cnt);
} else {
cnt = 0;
}
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(n), wherenis the length of the array, since we scan the array once. - 🧺 Space complexity:
O(1), as only a few variables are used.