LeetCode Solution: 485. Max Consecutive Ones

# leetcode# dsa# programming# tutorial
LeetCode Solution: 485. Max Consecutive OnesVansh Aggarwal

Unraveling Max Consecutive Ones: Your First LeetCode Stride! Hello awesome developers and...

Unraveling Max Consecutive Ones: Your First LeetCode Stride!

Hello awesome developers and aspiring competitive programmers! 👋

Vansh here, and today we're going to dive into a super common, yet incredibly foundational, LeetCode problem: 485. Max Consecutive Ones. This problem is a fantastic starting point for anyone looking to build their problem-solving muscles, especially with arrays. It teaches you to think about tracking state and making decisions as you iterate through data.

Ready to conquer your next coding challenge? Let's go!


The Problem: Max Consecutive Ones Explained

Imagine you have a list of numbers, but these aren't just any numbers – they're binary! This means each number is either a 0 or a 1. Your goal is simple: find the longest uninterrupted streak of 1s in this list.

Let's look at the official problem statement:

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: Here, we have two streaks of 1s: [1,1] (length 2) and [1,1,1] (length 3). The maximum is 3.

Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 2
Explanation: Streaks are [1] (length 1), [1,1] (length 2), [1] (length 1). The maximum is 2.

Constraints:

  • 1 <= nums.length <= 10^5 (The array won't be empty and won't be super huge)
  • nums[i] is either 0 or 1. (Only binary values, as expected!)

Seems straightforward enough, right? Let's think about how we'd tackle this.


The Intuition: Keeping Your Score!

Think about playing a game where you score points for every consecutive "hit" you make. If you miss, your current score resets, but you still remember your "personal best" score from previous streaks.

That's the core idea here! As we walk through the array:

  1. If we see a 1: "Hit!" 🎉 We're on a streak, so we extend our current consecutive count.
  2. If we see a 0: "Miss!" 😩 Our current streak is broken. At this point, we need to compare our current streak length with the maximum streak length we've seen so far and update our "personal best" if the current one was better. Then, we reset our current streak counter to zero, ready for a new streak.

Don't forget the very end! What if the array ends with a streak of 1s? We need one final check to see if that last streak beat our overall maximum.


The Approach: Step-by-Step Logic

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

  1. Initialize two variables:

    • max_consecutive: This will store the maximum number of consecutive 1s we've found globally so far. Initialize it to 0.
    • current_consecutive: This will track the number of consecutive 1s in the current streak we are examining. Initialize it to 0.
  2. Iterate through the nums array: Go through each number one by one.

  3. Inside the loop, for each num:

    • If num is 1:
      • Increment current_consecutive by 1. We're extending our current streak!
    • If num is 0:
      • The current streak of 1s is broken. First, we need to see if this current_consecutive streak was the best one we've found yet. So, update max_consecutive = max(max_consecutive, current_consecutive).
      • Then, reset current_consecutive back to 0 because a new streak (if any) will start from scratch after this 0.
  4. After the loop finishes:

    • It's possible that the array ended with a sequence of 1s. For example, [1,1,1]. The loop would finish with current_consecutive being 3, but max_consecutive might still be 0 (if this was the only streak) or some smaller number from an earlier streak.
    • So, perform one final update: max_consecutive = max(max_consecutive, current_consecutive). This ensures we capture any trailing streaks.
  5. Return max_consecutive: This will be your answer!


The Code: Bringing it to Life (C++)

Here's how we can implement this approach in C++:

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

class Solution {
public:
    int findMaxConsecutiveOnes(std::vector<int>& nums) {
        // Initialize variables to keep track of counts
        int max_consecutive = 0;   // Stores the overall maximum consecutive ones found
        int current_consecutive = 0; // Stores the count of ones in the current streak

        // Iterate through each number in the input array
        for (int num : nums) {
            if (num == 1) {
                // If the current number is 1, increment the current streak count
                current_consecutive++;
            } else {
                // If the current number is 0, the streak of 1s is broken.
                // 1. Update max_consecutive if the current streak was longer
                max_consecutive = std::max(max_consecutive, current_consecutive);
                // 2. Reset current_consecutive for the next potential streak
                current_consecutive = 0;
            }
        }

        // After the loop, there might be a trailing sequence of 1s.
        // We need one final check to update max_consecutive if the last streak was the longest.
        max_consecutive = std::max(max_consecutive, current_consecutive);

        // Return the overall maximum found
        return max_consecutive;
    }
};

Enter fullscreen mode Exit fullscreen mode

Time & Space Complexity Analysis

Understanding how efficient your code is, is a crucial skill in competitive programming and software development!

  • Time Complexity: O(N)

    • We iterate through the input array nums exactly once. If N is the number of elements in nums, we perform a constant amount of work (comparison, increment, max operation) for each element.
    • Therefore, the time taken grows linearly with the size of the input array.
  • Space Complexity: O(1)

    • We only use a few extra variables (max_consecutive, current_consecutive) to store counts. The number of these variables does not depend on the size of the input array nums.
    • Hence, the space used is constant, regardless of N. This is super efficient!

Key Takeaways

  • State Tracking: Many array problems involve keeping track of a "current state" (like current_consecutive) and comparing it against a "best state found so far" (like max_consecutive).
  • Edge Cases: Always consider what happens at the very beginning and, critically, at the very end of your input (like handling the trailing sequence of ones).
  • Single Pass: This problem demonstrates a common pattern where you can solve a problem by iterating through the input just once, leading to optimal O(N) time complexity.
  • Simple is Often Best: While there might be more complex ways to solve this, the direct, intuitive approach is often the most efficient and easiest to understand.

That's it! You've just solved your first (or next!) LeetCode problem, understood its logic, and analyzed its efficiency. Keep practicing, and these concepts will become second nature. Happy coding!


Author Account: Vansh2710
Time Published: 2026-05-09 15:49:48