Java one pass straightforward solution


  • 0
    C
        //The idea is to scan once and keep to variable, one for the previous consecutive ones,
        //the other is previous consecutive ones with one flip
        public int findMaxConsecutiveOnes(int[] nums) {
            int max = 0;
            int prevOnes = 0;
            int prevOnesWithOneFlip = 0;
            for (int i = 0; i < nums.length; ++i) {
                if (nums[i] == 1) {
                    ++prevOnes;
                    ++prevOnesWithOneFlip;
                }
                else {
                    prevOnesWithOneFlip = prevOnes + 1;
                    prevOnes = 0;
                }
                max = Math.max(max, prevOnesWithOneFlip);
            }
            return max;
        }
    

Log in to reply
 

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