Input: nums =[1,0,1,1,0]Output: 4Explanation:
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.The max number of consecutive ones is4.
Example 2:
1
2
3
4
5
6
Input: nums =[1,0,1,1,0,1]Output: 4Explanation:
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.The max number of consecutive ones is4.
Constraints:
1 <= nums.length <= 10^5
nums[i] is either 0 or 1.
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?
We want the longest sequence of 1s, allowing at most one 0 to be flipped to 1. By using a sliding window, we can efficiently track the window containing at most one 0 and update the maximum length found.
classSolution {
public:int findMaxConsecutiveOnes(vector<int>& nums) {
int l =0, ans =0, zero =0;
for (int r =0; r < nums.size(); ++r) {
if (nums[r] ==0) zero++;
while (zero >1) {
if (nums[l++] ==0) zero--;
}
ans = max(ans, r - l +1);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
funcfindMaxConsecutiveOnes(nums []int) int {
l, ans, zero:=0, 0, 0forr, x:=rangenums {
ifx==0 {
zero++ }
forzero > 1 {
ifnums[l] ==0 {
zero-- }
l++ }
ifr-l+1 > ans {
ans = r-l+1 }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
publicintfindMaxConsecutiveOnes(int[] nums) {
int l = 0, ans = 0, zero = 0;
for (int r = 0; r < nums.length; r++) {
if (nums[r]== 0) zero++;
while (zero > 1) {
if (nums[l++]== 0) zero--;
}
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funfindMaxConsecutiveOnes(nums: IntArray): Int {
var l = 0var ans = 0var zero = 0for (r in nums.indices) {
if (nums[r] ==0) zero++while (zero > 1) {
if (nums[l++] ==0) zero-- }
ans = maxOf(ans, r - l + 1)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
deffindMaxConsecutiveOnes(self, nums: list[int]) -> int:
l = ans = zero =0for r, x in enumerate(nums):
if x ==0:
zero +=1while zero >1:
if nums[l] ==0:
zero -=1 l +=1 ans = max(ans, r - l +1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnfind_max_consecutive_ones(nums: Vec<i32>) -> i32 {
let (mut l, mut ans, mut zero) = (0, 0, 0);
for (r, &x) in nums.iter().enumerate() {
if x ==0 {
zero +=1;
}
while zero >1 {
if nums[l] ==0 {
zero -=1;
}
l +=1;
}
ans = ans.max(r asi32- l asi32+1);
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
findMaxConsecutiveOnes(nums: number[]):number {
letl=0, ans=0, zero=0;
for (letr=0; r<nums.length; r++) {
if (nums[r] ===0) zero++;
while (zero>1) {
if (nums[l++] ===0) zero--;
}
ans= Math.max(ans, r-l+1);
}
returnans;
}
}