O(n) Solution with explaination


  • 0
    X
        public int findMaxConsecutiveOnes(int[] nums) {
            int p = -1;
            int cnt = 0;
            int max = 0;
            for(int i = 0; i < nums.length; i++){
                if(nums[i] == 1) cnt++;
                else{
                    cnt = i - p;
                    p = i;
                }
                max = Math.max(max, cnt);
            }
            return max;
        }
    }```
    the only thing we need to store is the location of the last 0, using this last 0, we can get the current count.

Log in to reply
 

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