[Leetcode] 487. Max Consecutive Ones II 解题报告

给定一个二进制数组,找到最多能翻转一次0的情况下,连续1的最大数量。文章介绍了题意、示例、解题思路,并给出了O(n)时间复杂度、O(1)空间复杂度的解决方案,适用于处理无限数据流的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0.

Example 1:

Input: [1,0,1,1,0]
Output: 4
Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
    After flipping, the maximum number of consecutive 1s is 4.

Note:

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

Follow up:
What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?

思路

由于可以允许翻转一次0,所以我们记录两部分内容:zeroLeft表示在需要翻转的0之前的连续1的个数,zeroRight表示在需要翻转的0之后的连续1的个数。一旦我们遇到一个0,就需要更新zeroLeft和zeroRight了。最终只要记录下来zeroLeft + zeroRight的最大值即可。注意到这里我们让zeroRight同时包含了需要翻转的0,这样就可以统一处理只有一个0的情况了。算法的时间复杂度是O(n),空间复杂度是O(1)。由于我们不需要对原来出现的数据进行重新存取,所以这个代码也满足了Follow up的要求,可以处理无限长的数据流。

代码

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int maxConsecutive = 0, zeroLeft = 0, zeroRight = 0;
        for (int i = 0; i < nums.size(); ++i) {
            ++zeroRight;
            if (nums[i] == 0) {
                zeroLeft = zeroRight;
                zeroRight = 0;
            }
            maxConsecutive = max(maxConsecutive, zeroLeft + zeroRight); 
        }
        return maxConsecutive;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值