algoadvance

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

Clarifying Questions

  1. Constraints on Length of Array: What is the maximum length of the array?
    • The problem does not explicitly state this, but we can assume the array length can be quite large (up to (10^5) elements).
  2. Array Contents: Can the array contain negative numbers or numbers other than 0 or 1?
    • No, the array is strictly binary, containing only 0s and 1s.
  3. Empty Array: What should be the output if the array is empty?
    • If the array is empty, there are no consecutive ones, so the output should be 0.

Strategy

  1. Initialize Counters: We’ll use two variables: one to keep track of the current streak of consecutive 1s and another to store the maximum streak found.
  2. Iterate Through Array: We’ll loop through the array. For each element:
    • If it’s 1, increment the current streak counter.
    • If it’s 0, update the maximum streak if the current streak is greater and reset the current streak counter.
  3. Final Check: After the loop, check the current streak one last time to update the maximum streak if needed.
  4. Result: The maximum streak counter will hold our result.

Code

def findMaxConsecutiveOnes(nums):
    max_consecutive = 0
    current_streak = 0

    for num in nums:
        if num == 1:
            current_streak += 1
            max_consecutive = max(max_consecutive, current_streak)
        else:
            current_streak = 0

    return max_consecutive

Time Complexity

The time complexity of this approach is ( O(n) ), where ( n ) is the length of the array. This is because we iterate through the array once, performing constant-time operations for each element.

The space complexity is ( O(1) ) since we are using a fixed amount of extra space regardless of the input size.

Try our interview co-pilot at AlgoAdvance.com