Simple Java Solution O(n) and O(1)


  • 0
    F

    Use variable index to record the position of zero, and initiate the index to -1. Once we find a zero, refresh the count and store the new index.

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int max = 0, count = 0, index = -1;
            for(int i = 0;i< nums.length; i++){
                if(nums[i] == 1){
                    count++;
                }else{
                    count = i - index;
                    index = i;
                }
                max = Math.max(max,count);
            }
            return max;
        }
    }
    

Log in to reply
 

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