内容中心

2026年比较好的山东农业灌溉泵站可靠供应商推荐-山东朝启电子科技有限公司

To solve this problem, we need to find the maximum number of consecutive 1s in a binary array. The approach involves tracking the current streak of consecutive 1s and updating the maximum streak whenever the current streak exceeds the previous maximum.

Approach

  1. Initialization:

    • current_streak: To keep track of the length of the current consecutive 1s.
    • max_streak: To store the maximum length of consecutive 1s encountered so far.
  2. Iterate through the array:

    • For each element in the array:
      • If the element is 1, increment current_streak and update max_streak if current_streak is greater than max_streak.
      • If the element is 0, reset current_streak to 0 (since the consecutive streak of 1s breaks here).
  3. Return the result: After processing all elements, max_streak will hold the desired value.

Solution Code

def findMaxConsecutiveOnes(nums):
    current_streak = 0
    max_streak = 0
    for num in nums:
        if num == 1:
            current_streak += 1
            if current_streak > max_streak:
                max_streak = current_streak
        else:
            current_streak = 0
    return max_streak

Explanation

  • Time Complexity: O(n) where n is the length of the array. We traverse the array once, making this solution efficient.
  • Space Complexity: O(1) since we only use a few variables to track the streaks, no additional data structures are needed.

This approach ensures that we efficiently find the maximum consecutive 1s with optimal time and space complexity. It handles all edge cases, including arrays with all 0s, all 1s, or a mix of both. For example:

  • Input: [1,1,0,1,1,1] → Output:3 (the last three 1s)
  • Input: [0,0,0] → Output:0
  • Input: [1] → Output:1

This solution is straightforward and effective for the given problem.

山东朝启电子科技有限公司

山东朝启电子科技有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?