Magicsheet logo

Max Consecutive Ones

Easy
48.3%
Updated 6/1/2025

Max Consecutive Ones

What is this problem about?

The Max Consecutive Ones problem gives you a binary array (containing only 0s and 1s). Your task is simple: find and return the maximum number of consecutive 1s present in the array. For instance, in the array [1, 1, 0, 1, 1, 1], the longest sequence of 1s has a length of 3.

Why is this asked in interviews?

This is a classic entry-level warmup question. Interviewers use it to ensure candidates understand basic array traversal, loop constructs, and local vs. global variable tracking. It is a fundamental building block; solving this fluidly shows you are ready to tackle more complex Sliding Window or state-machine problems.

Algorithmic pattern used

This problem relies on a straightforward Linear Scan / State Tracking pattern. You maintain two integer variables: a current_count to track the length of the current streak of 1s, and a max_count to record the highest streak seen so far. As you iterate through the array, you increment current_count if the element is 1. If the element is 0, you update max_count and reset current_count to 0.

Example explanation

Array: [1, 0, 1, 1, 0, 1] Initialize current_count = 0, max_count = 0.

  • Index 0 (1): current_count becomes 1. max_count becomes 1.
  • Index 1 (0): Streak breaks. current_count resets to 0.
  • Index 2 (1): current_count becomes 1.
  • Index 3 (1): current_count becomes 2. max_count updates to 2.
  • Index 4 (0): Streak breaks. current_count resets to 0.
  • Index 5 (1): current_count becomes 1. End of array. The highest max_count recorded is 2.

Common mistakes candidates make

A very common mistake for beginners is forgetting to update the max_count if the longest streak happens at the very end of the array. If the array is [0, 1, 1], the loop finishes while current_count is 2, but the max_count update logic might only be placed inside the if (num == 0) block. You must ensure max_count is updated dynamically on every 1, or explicitly do a final check after the loop ends.

Interview preparation tip

For the Max Consecutive Ones coding problem, keep the logic concise. Use Math.max(max_count, current_count) directly inside the if (num == 1) block. It eliminates the need for post-loop checks and proves you can write clean, resilient code that naturally handles edge cases like arrays filled entirely with 1s.

Similar Questions