Java O(n) AC Solution


  • 0
    A
    public int findMaxConsecutiveOnes(int[] nums) {
            int numOnes = 0, maxOnes = 0;
            
            for (int i = 0; i < nums.length; i++) {
                if (i > 0 && nums[i] != nums[i-1] && nums[i-1] == 1) {
                    maxOnes = Math.max(maxOnes, numOnes);
                    numOnes = 0;
                } else if (nums[i] == 1) {
                    numOnes++;
                }
            }
            
            maxOnes = Math.max(maxOnes, numOnes);
            return maxOnes;
        }
    

Log in to reply
 

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