Talentd
FleetCode
Make and follow sheets.Sign in

Max Consecutive Ones solution and explanation

EasyArray4 min read66.0% acceptanceUpdated 9 Apr 2026
LeetCode Max Consecutive Ones Solution Explained - JavaNick White · 3:53 · 18K viewsWatch on YouTube
9 more videos on this problem
  1. LeetCode Max Consecutive Ones Solution Explained - JavaNick White · 3:53 · 18K views
  2. Max Consecutive Ones | Leetcode 485Technosage · 6:44 · 11K views
  3. Max Consecutive Ones (LeetCode 485) | Full Solution w/ Kadane's Algorithm | Visuals and AnimationsNikhil Lohia · 14:12 · 6K views
  4. Leetcode - Max Consecutive Ones (Python)Timothy H Chang · 2:52 · 5K views
  5. [Java] Leetcode 485/487/1004. Max Consecutive Ones I/II/III [Sliding Windows #5]Eric Programming · 23:17 · 5K views
  6. Max Consecutive Ones | LeetCode 485 | ArrayNaresh Gupta · 5:31 · 1K views
  7. Max Consecutive Ones LeetCode 485 | Easy & Clear Explanation for BeginnersCodingNinja · 13:42 · 1K views
  8. Max Consecutive Ones - 485. LeetCode - JavaTeddy Smith · 6:49 · 627 views
  9. Max Consecutive Ones | c++ | Leetcode 485 | ArrayDe-Kode Programming · 4:58 · 332 views
  10. How to Solve "485 Max Consecutive Ones" on LeetCode? - JavascriptBecoming A Better Dev (with David) · 4:12 · 317 views

The problem

Given a binary array nums, return the maximum number of consecutive 1's in the array.

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 <= 105
  • nums[i] is either 0 or 1.

Approach overview

Problem Overview: You receive a binary array containing only 0 and 1. The task is to return the maximum number of consecutive 1s in the array. Each 0 breaks a streak, so you need to track the longest continuous segment of 1s while scanning the array.

Approach 1: Simple Iterative Count (Time: O(n), Space: O(1))

The simplest solution scans the array once while maintaining two counters: currentStreak and maxStreak. When you encounter a 1, increment currentStreak. When a 0 appears, reset currentStreak to zero because the consecutive sequence is broken. After each step, update maxStreak with max(maxStreak, currentStreak). This approach works because every element contributes to exactly one streak calculation. Since the array is processed with a single pass and no extra data structures, the time complexity is O(n) and space complexity is O(1). This pattern appears frequently in array traversal problems where you track a running segment length.

Approach 2: Sliding Window Technique (Time: O(n), Space: O(1))

You can also view the problem through the lens of a sliding window. Maintain two pointers representing the current window of consecutive 1s. Expand the right pointer while elements are 1. When a 0 appears, move the left pointer to the position after the zero and restart the window. At each step, compute the window length right - left + 1 and track the maximum. Although this produces the same complexity as the iterative counter, the sliding window interpretation becomes useful when the problem evolves—for example, allowing one or more zero flips (as in Max Consecutive Ones II and III). The algorithm still processes each element once, giving O(n) time and O(1) space.

Recommended for interviews: The iterative counting approach is what most interviewers expect because it demonstrates clean linear traversal and state tracking. It solves the problem with minimal logic and constant memory. The sliding window version shows deeper pattern recognition and prepares you for harder variants where the window must tolerate a limited number of zeros. Mentioning both approaches signals strong understanding of common array patterns and how they generalize to window-based problems.

Approach 1: Simple Iterative Count

This approach involves iterating through the array and counting sequences of 1s. If a 0 is encountered, the count is reset to 0. We keep track of the maximum count during the iteration.

def findMaxConsecutiveOnes(nums):
    maxCount = 0
    currentCount = 0
    for num in nums:
        if num == 1:
            currentCount += 1
            maxCount = max(maxCount, currentCount)
        else:
            currentCount = 0
    return maxCount

nums = [1, 1, 0, 1, 1, 1]
print("The maximum number of consecutive 1s is:", findMaxConsecutiveOnes(nums))
public class MaxConsecutiveOnes {
    public static int findMaxConsecutiveOnes(int[] nums) {
        int maxCount = 0, currentCount = 0;
        for (int num : nums) {
            if (num == 1) {
                currentCount++;
                maxCount = Math.max(maxCount, currentCount);
            } else {
                currentCount = 0;
            }
        }
        return maxCount;
    }

    public static void main(String[] args) {
        int[] nums = {1, 1, 0, 1, 1, 1};
        System.out.println("The maximum number of consecutive 1s is: " + findMaxConsecutiveOnes(nums));
    }
}
#include <iostream>
#include <vector>

int findMaxConsecutiveOnes(std::vector<int>& nums) {
    int maxCount = 0, currentCount = 0;
    for(int num : nums) {
        if(num == 1) {
            currentCount++;
            maxCount = std::max(maxCount, currentCount);
        } else {
            currentCount = 0;
        }
    }
    return maxCount;
}

int main() {
    std::vector<int> nums = {1, 1, 0, 1, 1, 1};
    std::cout << "The maximum number of consecutive 1s is: " << findMaxConsecutiveOnes(nums) << std::endl;
    return 0;
}
function findMaxConsecutiveOnes(nums) {
    let maxCount = 0;
    let currentCount = 0;
    for(let num of nums) {
        if(num === 1) {
            currentCount++;
            maxCount = Math.max(maxCount, currentCount);
        } else {
            currentCount = 0;
        }
    }
    return maxCount;
}

let nums = [1, 1, 0, 1, 1, 1];
console.log(`The maximum number of consecutive 1s is: ${findMaxConsecutiveOnes(nums)}`);
#include <stdio.h>

int findMaxConsecutiveOnes(int* nums, int numsSize) {
    int maxCount = 0, currentCount = 0;
    for(int i = 0; i < numsSize; i++) {
        if(nums[i] == 1) {
            currentCount++;
            if(currentCount > maxCount) {
                maxCount = currentCount;
            }
        } else {
            currentCount = 0;
        }
    }
    return maxCount;
}

int main() {
    int nums[] = {1, 1, 0, 1, 1, 1};
    int size = sizeof(nums) / sizeof(nums[0]);
    int result = findMaxConsecutiveOnes(nums, size);
    printf("The maximum number of consecutive 1s is: %d\n", result);
    return 0;
}
using System;

public class MaxConsecutiveOnes {
    public static int FindMaxConsecutiveOnes(int[] nums) {
        int maxCount = 0, currentCount = 0;
        foreach (int num in nums) {
            if (num == 1) {
                currentCount++;
                maxCount = Math.Max(maxCount, currentCount);
            } else {
                currentCount = 0;
            }
        }
        return maxCount;
    }

    public static void Main() {
        int[] nums = {1, 1, 0, 1, 1, 1};
        Console.WriteLine("The maximum number of consecutive 1s is: " + FindMaxConsecutiveOnes(nums));
    }
}

This Python code iterates through the list nums, updating counts similarly to previous implementations. It's straightforward with the use of Python's built-in max function.

Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Try this approach in the editor

Approach 2: Sliding Window Technique

This approach uses a variation of the sliding window technique. The idea is to maintain a window of the current sequence of 1s and adjust the window whenever a 0 is encountered.

def findMaxConsecutiveOnes(nums):
    left = 0
    maxCount = 0
    for right in range(len(nums)):
        if nums[right] == 0:
            left = right + 1
        maxCount = max(maxCount, right - left + 1)
    return maxCount

nums = [1, 0, 1, 1, 0, 1]
print("The maximum number of consecutive 1s is:", findMaxConsecutiveOnes(nums))
public class MaxConsecutiveOnes {
    public static int findMaxConsecutiveOnes(int[] nums) {
        int left = 0, right = 0, maxCount = 0;
        while (right < nums.length) {
            if (nums[right] == 0) {
                left = right + 1;
            }
            maxCount = Math.max(maxCount, right - left + 1);
            right++;
        }
        return maxCount;
    }

    public static void main(String[] args) {
        int[] nums = {1, 0, 1, 1, 0, 1};
        System.out.println("The maximum number of consecutive 1s is: " + findMaxConsecutiveOnes(nums));
    }
}
#include <iostream>
#include <vector>
using namespace std;

int findMaxConsecutiveOnes(vector<int>& nums) {
    int left = 0, right = 0, maxCount = 0;
    while (right < nums.size()) {
        if (nums[right] == 0) {
            left = right + 1;
        }
        maxCount = max(maxCount, right - left + 1);
        ++right;
    }
    return maxCount;
}

int main() {
    vector<int> nums = {1, 0, 1, 1, 0, 1};
    cout << "The maximum number of consecutive 1s is: " << findMaxConsecutiveOnes(nums) << endl;
    return 0;
}
function findMaxConsecutiveOnes(nums) {
    let left = 0;
    let maxCount = 0;
    for (let right = 0; right < nums.length; right++) {
        if (nums[right] === 0) {
            left = right + 1;
        }
        maxCount = Math.max(maxCount, right - left + 1);
    }
    return maxCount;
}

let nums = [1, 0, 1, 1, 0, 1];
console.log(`The maximum number of consecutive 1s is: ${findMaxConsecutiveOnes(nums)}`);
#include <stdio.h>

int findMaxConsecutiveOnes(int* nums, int numsSize) {
    int left = 0, right = 0;
    int maxCount = 0;
    while (right < numsSize) {
        if (nums[right] == 0) {
            left = right + 1;
        }
        maxCount = (right - left + 1 > maxCount) ? (right - left + 1) : maxCount;
        right++;
    }
    return maxCount;
}

int main() {
    int nums[] = {1, 0, 1, 1, 0, 1};
    int size = sizeof(nums) / sizeof(nums[0]);
    int result = findMaxConsecutiveOnes(nums, size);
    printf("The maximum number of consecutive 1s is: %d\n", result);
    return 0;
}
using System;

public class MaxConsecutiveOnes {
    public static int FindMaxConsecutiveOnes(int[] nums) {
        int left = 0, maxCount = 0;
        for (int right = 0; right < nums.Length; right++) {
            if (nums[right] == 0) {
                left = right + 1;
            }
            maxCount = Math.Max(maxCount, right - left + 1);
        }
        return maxCount;
    }

    public static void Main() {
        int[] nums = {1, 0, 1, 1, 0, 1};
        Console.WriteLine("The maximum number of consecutive 1s is: " + FindMaxConsecutiveOnes(nums));
    }
}

This Python solution applies the same technique using the right index iterating over the list, dynamically adjusting the left boundary when it hits zero.

Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Try this approach in the editor

Approach 3: Single Pass

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).

function findMaxConsecutiveOnes(nums: number[]): number {
    let [ans, cnt] = [0, 0];
    for (const x of nums) {
        if (x) {
            ans = Math.max(ans, ++cnt);
        } else {
            cnt = 0;
        }
    }
    return ans;
}
func findMaxConsecutiveOnes(nums []int) (ans int) {
	cnt := 0
	for _, x := range nums {
		if x == 1 {
			cnt++
			ans = max(ans, cnt)
		} else {
			cnt = 0
		}
	}
	return
}
impl Solution {
    pub fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
        let mut ans = 0;
        let mut cnt = 0;

        for &x in nums.iter() {
            if x == 1 {
                cnt += 1;
                ans = ans.max(cnt);
            } else {
                cnt = 0;
            }
        }

        ans
    }
}
class Solution {
    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function findMaxConsecutiveOnes($nums) {
        $ans = $cnt = 0;

        foreach ($nums as $x) {
            if ($x == 1) {
                $cnt += 1;
                $ans = max($ans, $cnt);
            } else {
                $cnt = 0;
            }
        }

        return $ans;
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Simple Iterative Count

Time Complexity: O(n)
Space Complexity: O(1)

Sliding Window Technique

Time Complexity: O(n)
Space Complexity: O(1)

Single Pass–

Complexity analysis

ApproachTimeSpaceWhen to Use
Simple Iterative CountO(n)O(1)Best general solution. Minimal logic and ideal for interviews.
Sliding Window TechniqueO(n)O(1)Useful when extending to variants allowing zero flips or variable window constraints.

Frequently asked questions

Is Max Consecutive Ones easy or hard?

Max Consecutive Ones is classified as an Easy problem on LeetCode with an acceptance rate above 60%. The challenge focuses on clean iteration and tracking a running segment length rather than complex algorithms.

How to solve Max Consecutive Ones in O(n)?

Iterate through the binary array while maintaining two variables: current streak and maximum streak. Increment the current streak when the value is 1, otherwise reset it to zero. Update the maximum after each step. This guarantees O(n) time and constant memory usage.

Max Consecutive Ones Python or Java solution?

Python and Java solutions both follow the same logic: iterate through the array, update a running count of consecutive ones, and reset on zeros. The implementation typically fits in a few lines and runs in O(n) time with O(1) space.

What is the best approach for Max Consecutive Ones?

The optimal approach is a single-pass iterative counter. Traverse the array, increase a running counter when you see a 1, and reset it when a 0 appears. Track the maximum streak during the traversal. This runs in O(n) time and O(1) space.

What data structure is used in Max Consecutive Ones?

The problem primarily uses a simple array traversal with integer counters. No additional data structures are required. Some explanations frame the logic using the sliding window technique, but it still operates directly on the array with constant extra space.

What is the time complexity of Max Consecutive Ones?

The standard solution runs in O(n) time because the array is scanned once from left to right. Each element is processed exactly one time. Space complexity remains O(1) since only a few integer counters are maintained.

Is Max Consecutive Ones asked at Google, Amazon, or Meta?

Max Consecutive Ones is a common entry-level array problem and has appeared in interview prep lists associated with companies like Amazon and Google. It is often used to test basic array traversal, state tracking, and understanding of sliding window patterns.

Comments

Now write it yourselfClose this page and solve Max Consecutive Ones in the editor, without looking.
Practise Max Consecutive Ones