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.

  1. The input array will only contain 0 and 1.

  2. The length of input array is a positive integer and will not exceed 10,000.

Example

Example 1:
	Input:  nums = [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.

Example 2:
	Input: nums = [1,0,1,0,1]
	Output:  3
	
	Explanation:
	Flip each zero will get the the maximum number of consecutive 1s.
	After flipping, the maximum number of consecutive 1s is 3.
public class Solution {

    public int findMaxConsecutiveOnes(int[] nums) {
        boolean isFlipped = false;
        int max = 0, start = 0, end = 0;
        while (end < nums.length) {
            if (nums[end] == 0) {
                if (!isFlipped)
                    isFlipped = true;
                else {
                    while (nums[start] != 0)
                        start++;
                    start++;
                }
            }
            max = Math.max(max, end - start + 1);
            end++;
        }
        return max;
    }
}

Last updated