Python 0485.py
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
result = 0
current = 0
for i in nums:
if i == 1:
current += 1
result = max(result, current)
else:
current = 0
return result
Difficulty
and has an acceptance rate of about 60% (2+ million submissions).
Typical patterns to solve this problem:
- Array
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic problem of determining the longest run of consecutive 1s in a binary array. It iterates through the input list once, maintaining a running count of the current streak of 1s and updating the best streak seen so far. The algorithm returns the length of the longest such streak.
Key Steps
Initialization
At the start of the method two integer variables are created.
result = 0
current = 0
result holds the maximum length discovered up to the current point, while current tracks the length of the ongoing sequence of 1s.
Iteration and Counting
The core of the solution is a single for loop that examines each element of the input list in order.
for i in nums:
if i == 1:
current += 1
result = max(result, current)
else:
current = 0
When the element equals 1, the algorithm increments current, reflecting the continuation of a streak. Immediately after the increment, result is refreshed with the larger of its previous value and the new current. If the element is 0, the ongoing streak is broken and current is reset to 0, preparing for any future streak that may begin later in the array.
Result Return
After the loop finishes, the method returns the stored maximum.
return result
This final value represents the length of the longest contiguous block of 1s encountered during the scan.
Edge Cases Handled
The logic gracefully deals with several boundary conditions without additional code.
When the input list is empty, the loop body never executes; both result and current remain at their initial value of 0, and the method returns 0, which correctly indicates that no 1s are present.
If the array consists entirely of 0s, each iteration triggers the else branch, repeatedly resetting current to 0. The result never changes from its initial 0, so the method again returns 0.
When the array is composed solely of 1s, the if branch runs for every element. current grows with each step, and result is updated to match current each time. At loop termination, result equals the length of the array, correctly reflecting the maximal streak.
Mixed patterns of 1s and 0s are handled by the alternating increment and reset behavior, ensuring that only contiguous runs contribute to the count.
Performance Optimizations
The implementation achieves optimal efficiency by using a single pass over the input data. Maintaining only two scalar variables (result and current) means that the algorithm’s memory footprint stays constant regardless of input size.
The use of the built-in max function to update result avoids explicit conditional branches for comparison, allowing the interpreter to handle the operation efficiently.
Resetting current to 0 immediately upon encountering a 0 eliminates the need for additional state tracking or auxiliary data structures, further reducing overhead.
Overall, the design leverages straightforward control flow and minimal state to deliver fast execution with negligible auxiliary memory usage.
ELI5 - Simplified Explanation
Imagine a long row of building blocks spread out on the floor. Some of these blocks are shiny gold ones labeled with a one, and others are plain gray ones labeled with a zero. The goal is to walk down the row and find the longest stretch of shiny gold blocks standing side by side.
A little helper starts at the beginning of the row, keeping a tally of how many gold blocks have been seen in a row. Every time a gold block is found, the helper adds one to the tally and writes down how high the tally reached if it is the biggest number seen so far. If a gray block appears instead, it means the current stretch has been broken, so the tally resets back to zero. By the time the end of the row is reached, the helper remembers the highest number written down during the walk.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Python | JS | Go | Rust | PHP | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 424: Longest Repeating Character Replacement
- problem 487: Max Consecutive Ones II
Solved On The Same Day
- problem 342: Power of Four
- problem 344: Reverse String
- problem 345: Reverse Vowels of a String
- problem 349: Intersection of Two Arrays
- problem 350: Intersection of Two Arrays II
- problem 387: First Unique Character in a String
- problem 412: Fizz Buzz
- problem 414: Third Maximum Number
- problem 434: Number of Segments in a String
- problem 448: Find All Numbers Disappeared in an Array
- problem 504: Base 7
- problem 507: Perfect Number
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality