Problem 1567

Abstract / Summary

Find the longest continuous part of the list where multiplying all numbers gives a result greater than zero.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
36 lines | 1207 bytes | submitted May 3, 2024 | GitHub   34% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Greedy
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 (+1 for even count of negatives, -1 for 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 - sign never flips, stays +1, and the function returns the full segment length.
  • Segments with a single negative number - first and last point 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 - first records the earliest negative, last the 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, sign remains +1 and length 1 is returned; if it is negative, first and last are 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; result stays at its initial value 0, which is the correct answer.
  • Empty input list - The padded zero still triggers the loop once; the slice nums[0:0] is empty, check receives an empty list, the loop inside check does not execute, sign stays +1, and len(sub) is 0, so the final result is 0.

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.22 | σ = 1.40

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
27 links | 16 authors | 7 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   May 3, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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