Python 1567.py
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
result = 0
# process an array without zeros
def check(sub):
best = 0
# first and last time a negative number was observed
first = None
last = None
sign = +1
for i, s in enumerate(sub):
# process only negative numbers
if s < 0:
sign = -sign
if first is None:
first = i
last = i
# whole subarray is positive
if sign == +1:
return len(sub)
# skip everything before (and including) the first negative number
# or everything after (and including) the last negative number
return max(len(sub) - (first + 1), last)
# partition into non-zero groups
start = 0
for end, n in enumerate(nums + [ 0 ]): # pad with zero to properly handle final partition
if n == 0:
result = max(result, check(nums[start : end]))
start = end + 1
return result
Difficulty
and has an acceptance rate of about 45% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Greedy
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 implementation computes the length of the longest contiguous sub-array whose product is positive. It treats zeros as natural separators because any sub-array containing a zero has a product of zero, which cannot be positive. The algorithm first splits the input list into maximal segments that contain no zeros, then evaluates each segment to determine the longest prefix or suffix that yields a positive product. The final answer is the maximum length found among all segments.
Partitioning the Input on Zeros
The outer loop walks through the original list while appending an extra zero at the end. This sentinel zero guarantees that the last non-zero segment is processed without requiring a separate finalization step.
start = 0
for end, n in enumerate(nums + [0]): # pad with zero to properly handle final partition
if n == 0:
result = max(result, check(nums[start:end]))
start = end + 1
When a zero is encountered, the slice nums[start:end] represents a contiguous block without zeros. The check helper is invoked on that block, and the running maximum result is updated. Afterwards the start index moves past the zero, beginning a new block.
Evaluating a Zero-Free Segment
The nested check function determines the longest sub-segment of its argument whose product is positive. It tracks three pieces of information while scanning the segment once:
sign- the cumulative sign of the product seen so far (+1for even count of negatives,-1for odd).first- the index of the first negative number encountered.last- the index of the most recent negative number.
def check(sub):
best = 0
first = None
last = None
sign = +1
for i, s in enumerate(sub):
if s < 0:
sign = -sign
if first is None:
first = i
last = i
If the final sign is positive (+1), the entire segment already has a positive product, and its full length is returned.
if sign == +1:
return len(sub)
When the sign is negative, the product of the whole segment is negative. To obtain a positive product, the algorithm discards either the prefix up to and including the first negative number or the suffix starting at the last negative number. The longer of the two remaining lengths is the answer for that segment.
return max(len(sub) - (first + 1), last)
Edge Cases Handled
- Segments without any negative numbers -
signnever flips, stays+1, and the function returns the full segment length. - Segments with a single negative number -
firstandlastpoint to the same index; the return expression evaluates the longer of dropping the prefix (leaving everything after the negative) or dropping the suffix (leaving everything before the negative). - Segments with multiple negatives -
firstrecords the earliest negative,lastthe latest. The parity of the total count of negatives determines whether the whole segment is positive or requires trimming. - Segments consisting of a single element - If that element is zero, it never reaches
check; if it is positive,signremains+1and length 1 is returned; if it is negative,firstandlastare both zero, and the return expression yields zero, correctly indicating no positive-product sub-array. - Input consisting entirely of zeros - The outer loop never calls
check;resultstays at its initial value0, which is the correct answer. - Empty input list - The padded zero still triggers the loop once; the slice
nums[0:0]is empty,checkreceives an empty list, the loop insidecheckdoes not execute,signstays+1, andlen(sub)is0, so the final result is0.
Performance Optimizations
The algorithm processes the input in a single forward pass, using only constant additional variables (result, start, first, last, sign). The inner check function also runs in linear time relative to the length of its segment, and each element of the original list participates in exactly one call to check. By avoiding nested loops over the entire array and by terminating each segment scan as soon as the segment ends, the implementation achieves optimal traversal efficiency.
The use of a sentinel zero eliminates the need for a separate post-loop handling of the final segment, simplifying control flow and reducing branching. The decision to compute the answer for a segment with a simple arithmetic expression (max(len(sub) - (first + 1), last)) avoids additional passes or auxiliary data structures, keeping the runtime overhead minimal.
ELI5 - Simplified Explanation
Imagine you have a long train of colored blocks that you are trying to group together. Some of the blocks are special because they are negative, like a grumpy block that turns everything it touches into a different color. Your goal is to find the longest stretch of blocks where all the negatives cancel each other out, making the whole bunch look just as happy and positive as can be.
The code first looks at all the blocks and breaks them into smaller groups whenever it hits a zero, which acts like a wall that stops the train. Once it has a group without any walls, it looks at the grumpy negative blocks inside. If there is an even number of grumpy blocks, they all cancel each other out, so the entire group stays happy and you can count them all. If there is an odd number of grumpy blocks, the group stays a little bit grumpy overall. To fix this, the code decides to either chop off everything from the very start up to the first grumpy block, or chop off everything from the last grumpy block to the very end. This leaves behind a smaller, perfectly happy chunk of blocks. By doing this for every group and keeping track of the biggest collection found, the code finds the longest possible happy train.
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 | Go | TS | |||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| FelixFan1122 | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| YuriSpiridonov | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| FelixFan1122 | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1319: Number of Operations to Make Network Connected
- problem 1465: Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
- problem 1477: Find Two Non-overlapping Sub-arrays Each With Target Sum
- problem 1482: Minimum Number of Days to Make m Bouquets
- problem 1488: Avoid Flood in The City
- problem 1524: Number of Sub-arrays With Odd Sum
- problem 1546: Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
- problem 1562: Find Latest Group of Size M
- problem 1320: Minimum Distance to Type a Word Using Two Fingers
- problem 1697: Checking Existence of Edge Length Limited Paths
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