487. Max Consecutive Ones II

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?

Solution:滑動窗[l, h]

思路:
這道題在之前那道題Max Consecutive Ones的基礎(chǔ)上加了一個條件,有一次將0翻轉(zhuǎn)成1的機會,問此時最大連續(xù)1的個數(shù)。
用一個變量cnt來記錄連續(xù)1的個數(shù),當(dāng)遇到了0的時候,因為我們有一次0變1的機會,所以我們遇到0了還是要累加cnt,然后我們此時需要用另外一個變量cur來保存當(dāng)前cnt的值,然后cnt重置為0,以便于讓cnt一直用來統(tǒng)計純連續(xù)1的個數(shù),然后我們每次都用用cnt+cur來更新結(jié)果res。

Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int max = 0, zero = 0, k = 1; // flip at most k zero
        for (int l = 0, h = 0; h < nums.length; h++) {
            if (nums[h] == 0)                                           
                zero++;
            while (zero > k)
                if (nums[l++] == 0)
                    zero--;                                     
            max = Math.max(max, h - l + 1);
        }                                                               
        return max;             
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容