We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Max Consecutive Ones

Number: 485

Difficulty: Easy

Paid? No

Companies: Google, Amazon, Meta, Bloomberg, Yandex, Accenture, Adobe, Apple, Microsoft


Problem Description

Given a binary array, return the maximum number of consecutive 1's in the array.


Key Insights

  • Iterate over the array while keeping track of the current sequence length of 1's.
  • Reset the counter when a 0 is encountered.
  • Update the maximum value during the iteration.
  • This direct scanning results in a simple O(n) solution with constant space.

Space and Time Complexity

Time Complexity: O(n) - We traverse the array once. Space Complexity: O(1) - Only constant extra variables are used.


Solution

We iterate through the binary array and maintain two counters: one for the current sequence of consecutive 1's (currentCount) and one for the maximum sequence found so far (maxConsecutive). As we scan the array, we increment currentCount when we see a 1 and update maxConsecutive. When a 0 is found, we reset currentCount to 0. This approach leverages a simple linear pass through the array and uses a constant amount of extra space.


Code Solutions

# Function to return maximum consecutive 1s in an array
def findMaxConsecutiveOnes(nums):
    # Initialize counters for consecutive ones
    max_consecutive = 0
    current_count = 0
    # Iterate through each number in the list
    for num in nums:
        if num == 1:
            # Increase the count when the current number is 1
            current_count += 1
            # Update maximum if the current count is higher
            max_consecutive = max(max_consecutive, current_count)
        else:
            # Reset current count when a 0 is encountered
            current_count = 0
    return max_consecutive

# Example usage:
if __name__ == "__main__":
    example_nums = [1, 1, 0, 1, 1, 1]
    print(findMaxConsecutiveOnes(example_nums))  # Expected output: 3
← Back to All Questions