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 is3.
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 is2.
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:
- Start reading from left to right.
- If you see a
1, you'd increase your "current streak" counter. - 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 the0. - Keep going until you reach the end of the paper.
- 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:
-
Initialize two variables:
-
max_consecutive_ones: This will store the overall maximum number of consecutive1s we've found so far. Start it at0. -
current_consecutive_ones: This will keep track of the count of1s in the current streak we are examining. Also start it at0.
-
Iterate through the
numsarray: We'll go through each number, one by one.-
Inside the loop, for each
num:- If
numis1: Incrementcurrent_consecutive_onesby1. We're extending our current streak! - If
numis0: Our current streak of1s has just ended.- First, we need to compare
current_consecutive_oneswithmax_consecutive_ones. Ifcurrent_consecutive_onesis greater, updatemax_consecutive_onesto this new, higher value. This ensuresmax_consecutive_onesalways holds the best streak found so far. - Then, reset
current_consecutive_onesback to0because the0has broken the streak, and we're ready to count a new one.
- First, we need to compare
- If
After the loop finishes: There's one last potential streak to consider! If the array ended with one or more
1s,current_consecutive_oneswill 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).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;
}
};
⏱️ Time & Space Complexity Analysis
Let's break down how efficient our solution is:
-
Time Complexity: O(N)
-
Nrefers to the number of elements in thenumsarray. - 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 arrayN. - This makes our solution very space-efficient!
- We only use a few extra variables (
🎯 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) andmax_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), all1s (current will build up toNand be correctly updated), and empty arrays (loop won't run, 0 is returned). The finalstd::maxafter 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)