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:


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:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int n = nums.length;
        int[][] dp = new int[n][2];
        if (nums[0] == 0) {
            dp[0][0] = 1;
            dp[0][1] = 0;
        } else {
            dp[0][0] = 1;
            dp[0][1] = 1;
        }
        int max = 1;
        for (int i = 1; i < n; i ++) {
            if (nums[i] == 0) {
                dp[i][0] = dp[i - 1][1] + 1;
                dp[i][1] = 0;
            } else {
                dp[i][0] = dp[i - 1][0] + 1;
                dp[i][1] = dp[i - 1][1] + 1;
            }
            max = Math.max(dp[i][0], Math.max(dp[i][1], max));
        }
        // for (int[] arr : dp)
        // System.out.println(Arrays.toString(arr));
        return max;
    }
}

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int n = nums.length;
        int zero = 0, one = 0;
        // int[][] dp = new int[n][2];
        if (nums[0] == 0) {
            zero = 1;
            one = 0;
        } else {
            zero = 1;
            one = 1;
        }
        int max = 1;
        for (int i = 1; i < n; i ++) {
            if (nums[i] == 0) {
                zero = one + 1;
                one = 0;
            } else {
                zero = zero + 1;
                one = one + 1;
            }
            max = Math.max(zero, Math.max(one, max));
        }
        // for (int[] arr : dp)
        // System.out.println(Arrays.toString(arr));
        return max;
    }
}