Python -- current cnt, previous cnt


  • 0
    B

    Part I only. For followup question, in addition to lastzero index, value of nums[lastzero-1] will have to be stored.

    class Solution(object):
        def findMaxConsecutiveOnes(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            maxcurr = 0
            prev = 0
            cnt  = 0
            lastzero = None
            if len(nums) < 1: return 0
            if sum(nums) == 0: return 1
            for idx, v in enumerate(nums):
                    if v != 1:
                            if prev == 0 and cnt != 0:
                                    prev = cnt
                                    maxcurr = max(maxcurr, cnt)
                                    lastzero = idx
                                    cnt = 0
                                    continue
                            elif lastzero and nums[lastzero-1] == 1:
                                    maxcurr = max(maxcurr, cnt + prev + 1)
                                    prev = cnt
                                    cnt = 0
                                    lastzero = idx
                                    continue
                            else:
                                    maxcurr = max(maxcurr, cnt)
                                    prev = 0
                                    cnt = 0
                                    lastzero = idx
                                    continue
                    cnt = cnt + 1
            if lastzero and nums[lastzero-1] == 1:
                    return max(maxcurr, cnt + prev + 1)
            elif sum(nums[:lastzero]) == 0:
                    return max(maxcurr, cnt) + 1
            else:
                    return max(maxcurr, cnt)
    

Log in to reply
 

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