Straightforward O(N) Java Solution with Follow-up Covered


  • 0

    The idea basically is till use two pointers, to support very long data stream, here I used newBegin to keep the next begin position, and hasFind to indicate if the zero has been set or not. The complete code is as follows.

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int max = 1;
            int begin = 0;
            int end = 0;
            int newBegin = 0;
            boolean findZero = false;
    
            while (end < nums.length) {
                while (end < nums.length && (nums[end] == 1 || !findZero)) {
                    if (nums[end] == 0) {
                        findZero = true;
                        newBegin = end + 1;
                    }
                    end++;
                }
                max = Math.max(max, end - begin);
                begin = newBegin;
                findZero = false;
            }
            return max;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.