my simple java solution


  • 0
    L

    // search a window that has at most 1 zeros, for each element, if it's 1 keep going, other wise, 1)if number of zerso is less than 1 , keep going and increment number of zeros by 1; 2) restart from the next element of previous 0, update current maximum

    public int findMaxConsecutiveOnes(int[] nums) {
        int curMax = 0, max = 0, previousZero = 0, numOfZeros = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] == 1) curMax++;
            else if(numOfZeros <1){
                numOfZeros++;
                curMax++;
                previousZero = i; // whenever meet a zero, update the position of previous zero
            } else {
                if(max < curMax) max = curMax;
                curMax = i - previousZero;
                previousZero = i; // whenever meet a zero, update the position of previous zero
            }
            
        }
        
        if(curMax > max) max = curMax;
        
        return max;

Log in to reply
 

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