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;
}
}