Logo
    Logo

    ©️ 2020-2026, Akhil Abraham.

    LinkedInGitHubMediumX
    Akhil Abraham
    Akhil Abraham
    /Posts
    Posts
    /LeetCode
    LeetCode
    /
    LeetCode
    /0485 - Max Consecutive Ones
    0485 - Max Consecutive Ones
    0485 - Max Consecutive Ones
    0485 - Max Consecutive Ones

    0485 - Max Consecutive Ones

    Difficulty
    Easy
    Language
    Python
    URL
    https://leetcode.com/problems/max-consecutive-ones/

    Solution 1 - Simple Traversal

    Traverse the array while maintaining a running count of consecutive 1s. When a 0 is encountered, reset the count. Track the maximum count seen throughout the traversal.

    TimeComplexity:O(n)TimeComplexity: O(n)TimeComplexity:O(n)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)
    """ 0485.1 - Solution 1 - Simple Traversal """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
            """Max Consecutive Ones Function"""
            max_count = 0
            current_count = 0
    
            for num in nums:
                if num == 1:
                    current_count += 1
                    max_count = max(max_count, current_count)
                else:
                    current_count = 0
    
            return max_count
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().findMaxConsecutiveOnes([1, 1, 0, 1, 1, 1]))  # Expected: 3
        print(Solution().findMaxConsecutiveOnes([1, 0, 1, 1, 0, 1]))  # Expected: 2
        print(Solution().findMaxConsecutiveOnes([0, 0, 0]))            # Expected: 0
        print(Solution().findMaxConsecutiveOnes([1]))                  # Expected: 1
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()