Python solution with detailed explanation


  • 0
    G

    Solution

    Max Consecutive Ones https://leetcode.com/problems/max-consecutive-ones/

    Algorithm 1

    • Maintain cnt to track the current run of 1s. Update the max_run after increment of cnt.
    • Reset cnt to 0 when we encounter 0 in the array.
    class Solution(object):
        def findMaxConsecutiveOnes(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            max_ones, cnt = 0, 0
            for x in nums:
                if x == 1:
                    cnt += 1
                    max_ones = max(max_ones, cnt)
                else:
                    cnt = 0
            return max_ones
    

    Algorithm 2

    • Maintain prev which tracks the index of last seen 0. Initialize prev to -1.
    • Do not forget to test for a run after the end of iteration.
    class Solution(object):
        def findMaxConsecutiveOnes(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            prev = -1
            max_ones = 0
            for i in range(len(nums)):
                if nums[i] == 0:
                    max_ones, prev = max(max_ones, i-prev-1), i
            if len(nums) and nums[-1] == 1:
                max_ones = max(max_ones, len(nums)-prev-1)
            return max_ones
    

Log in to reply
 

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