DEV Community

Vansh Aggarwal
Vansh Aggarwal

Posted on

LeetCode Solution: 485. Max Consecutive Ones

Level Up Your LeetCode: Tackling Max Consecutive Ones with Simple Logic

Hey there, fellow coding adventurers! 👋 Vansh2710 here, ready to dive into another LeetCode challenge. Today, we're looking at Problem 485: Max Consecutive Ones. This problem is a fantastic entry point for beginners to understand basic array traversal and state management. Don't let "LeetCode" intimidate you – we'll break it down piece by piece!


🧐 Problem Explanation: What are we actually doing?

Imagine you have a list of numbers, but these numbers can only be 0 or 1. This is what we call a binary array.

Your mission, should you choose to accept it (and you should! 😉), is to find the longest "streak" of 1s in that list. We want to know the maximum number of 1s that appear one after another.

Let's look at the examples:

Example 1:
nums = [1,1,0,1,1,1]

  • We see two 1s at the beginning: [1,1,...] (count: 2)
  • Then a 0.
  • Then three 1s: [...,1,1,1] (count: 3)
  • The maximum consecutive 1s is 3.

Example 2:
nums = [1,0,1,1,0,1]

  • One 1: [1,...] (count: 1)
  • Then a 0.
  • Two 1s: [...,1,1,...] (count: 2)
  • Then a 0.
  • One 1: [...,1] (count: 1)
  • The maximum consecutive 1s is 2.

Simple enough, right? We're essentially looking for the longest chain of 1s!


✨ Intuition: The "Aha!" Moment

How would you count the longest streak of 1s if I gave you a piece of paper with 0s and 1s?

You'd probably do something like this:

  1. Start reading from left to right.
  2. If you see a 1, you'd increase your "current streak" counter.
  3. If you see a 0, your current streak is broken! You'd then make a mental note: "Was my just-finished streak longer than any I've seen before?" If yes, update your "all-time longest streak" record. Then, you'd reset your "current streak" counter back to zero because you're starting fresh after the 0.
  4. Keep going until you reach the end of the paper.
  5. Crucially: What if the list ends with a streak of 1s? You need to make one final check to see if that very last streak was the longest one!

This thought process is the algorithm!


🛠️ Approach: Step-by-Step Logic

Let's formalize our intuition into a clear, step-by-step approach:

  1. Initialize two variables:

    • max_consecutive_ones: This will store the overall maximum number of consecutive 1s we've found so far. Start it at 0.
    • current_consecutive_ones: This will keep track of the count of 1s in the current streak we are examining. Also start it at 0.
  2. Iterate through the nums array: We'll go through each number, one by one.

  3. Inside the loop, for each num:

    • If num is 1: Increment current_consecutive_ones by 1. We're extending our current streak!
    • If num is 0: Our current streak of 1s has just ended.
      • First, we need to compare current_consecutive_ones with max_consecutive_ones. If current_consecutive_ones is greater, update max_consecutive_ones to this new, higher value. This ensures max_consecutive_ones always holds the best streak found so far.
      • Then, reset current_consecutive_ones back to 0 because the 0 has broken the streak, and we're ready to count a new one.
  4. After the loop finishes: There's one last potential streak to consider! If the array ended with one or more 1s, current_consecutive_ones will hold the count of that final streak. We need to perform one last comparison: max_consecutive_ones = std::max(max_consecutive_ones, current_consecutive_ones).

  5. Return max_consecutive_ones: This will be our final answer!


💻 Code

Here's the C++ implementation based on our approach:

#include <vector> // Required for std::vector
#include <algorithm> // Required for std::max

class Solution {
public:
    int findMaxConsecutiveOnes(std::vector<int>& nums) {
        // Variable to store the overall maximum consecutive ones found
        int max_consecutive_ones = 0;
        // Variable to store the count of ones in the current consecutive sequence
        int current_consecutive_ones = 0;

        // Iterate through each number in the input array 'nums'
        for (int num : nums) {
            if (num == 1) {
                // If the current number is 1, increment the current streak count
                current_consecutive_ones++;
            } else {
                // If the current number is 0, the streak of 1s is broken.
                // First, update the overall maximum if the current streak was longer.
                max_consecutive_ones = std::max(max_consecutive_ones, current_consecutive_ones);
                // Reset the current streak counter to 0, as we start fresh after a 0.
                current_consecutive_ones = 0;
            }
        }

        // IMPORTANT: After the loop, there might be a final sequence of 1s at the end
        // of the array whose count is still in 'current_consecutive_ones'.
        // We need one final comparison to ensure this last streak is considered for the maximum.
        max_consecutive_ones = std::max(max_consecutive_ones, current_consecutive_ones);

        // Return the overall maximum consecutive ones found
        return max_consecutive_ones;
    }
};

Enter fullscreen mode Exit fullscreen mode

⏱️ Time & Space Complexity Analysis

Let's break down how efficient our solution is:

  • Time Complexity: O(N)

    • N refers to the number of elements in the nums array.
    • We iterate through the array exactly once, performing a constant amount of work (a comparison and an increment/reset) for each element.
    • Therefore, the time taken grows linearly with the size of the input array. This is as efficient as it gets for this problem!
  • Space Complexity: O(1)

    • We only use a few extra variables (max_consecutive_ones, current_consecutive_ones) to store our counts. The amount of memory used does not depend on the size of the input array N.
    • This makes our solution very space-efficient!

🎯 Key Takeaways

  • Iterative Approach: Many array problems can be solved by simply iterating through them once, keeping track of relevant information as you go.
  • State Management: The power of current_consecutive_ones (our current state) and max_consecutive_ones (our global maximum) is evident here. Knowing what to track and when to update is crucial.
  • Handling Edge Cases (Implicitly): Our logic gracefully handles arrays with all 0s (max will remain 0), all 1s (current will build up to N and be correctly updated), and empty arrays (loop won't run, 0 is returned). The final std::max after the loop is key for sequences ending the array.
  • Simplicity Wins: This problem demonstrates that not all LeetCode problems require complex data structures or algorithms. Sometimes, a straightforward, intuitive approach is all you need!

Keep practicing, keep coding, and remember to always look for that "aha!" moment! Happy coding!


Vansh2710

Published: 2026-05-09 15:41:24

Top comments (0)