Understandable Java O(n) Time O(1) Space Solution


  • 0
    X
    public int findMaxConsecutiveOnes(int[] nums) 
    {
        if (nums == null) return 0;
        if (nums.length == 0) return 0;
        if (nums.length == 1) return 1;
        
        int cur = 0;
        int max = 0;
        int distance = 0;
        boolean countDistance = false;
        
        for (int i = 0; i < nums.length; i++)
        {
            if (nums[i] == 0)
            {
                if (countDistance) cur = 1 + distance;
                else cur++;
                
                // Reset the distance
                distance = 0;
                
                // Start counting distance from this 0.
                countDistance = true;
            }
            else
            {
                // Only count after seeing a 0.
                if (countDistance) distance++;
                
                cur++;
            }
            
            max = cur > max ? cur : max;
        }
        
        max = cur > max ? cur : max;
        return max;
    }
    

Log in to reply
 

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