My simple O(n) solution


  • 0
    B

    The idea here is to find the max distance between 0s.

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int lastZero = -1;
            int max = 0;
            for (int i = 0; i < nums.length; i++)
            {
                if (nums[i] == 0)
                {
                    max = Math.max(max, i - lastZero -1);
                    lastZero = i;
                }
            }
            max = Math.max(max, nums.length-lastZero-1);  //check number of 1s after the last 0
            return max;
        }
    }
    

Log in to reply
 

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