Java O(n) Time O(1) space solution


  • 0

    There is a corner case that nums has all 1s, no 0, that's the reason I set prevLen = -1.

        public int findMaxConsecutiveOnes(int[] nums) {
            int prevLen  = -1, curLen = 0, max = 0;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != 0) {
                    curLen++;
                } else {
                    prevLen = curLen;
                    curLen = 0;
                }
                max = Math.max(max, prevLen + curLen + 1);
            }
            
            return max;
        }
    

Log in to reply
 

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