Python, caching previous length, beat100%


  • 0
    L

    To cache previous length if we have only one zero in between.
    keep tracking the max length
    remember to decrement result when no zero for us to flip.

    prev = 0
            cur = 0
            count = 0
            hasZero = False
            for num in nums:
                if num == 1:
                    cur += 1
                else:
                    hasZero = True
                    if cur != 0:
                        count = max(count, 1 + prev + cur)
                        prev = cur
                        cur = 0
                    else:
                        prev = 0
            count = max(count, 1 + prev + cur)
            return count if hasZero else count-1
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.