O(n) solution which only looks at current number (works for streaming)


  • 0
    C
        public int findMaxConsecutiveOnes(int[] nums) {
            int count1=0;
            int count2=0;
            int max = 0;
            for(int i=0;i<nums.length;i++) {
                if (nums[i] == 1) {
                    count1++;
                    count2++;
                } else {
                    if (count1 != 0)
                        count2 = count1 + 1;
                    else
                        count2 = 1;
                    count1 = 0;
                }
                max = Math.max(Math.max(count1, count2), max);
            }
            return max;
        }
    

    Explanation:

    • Whenever you see 1, increment count1 and count2

    • Whenever you see zero, if this is first zero, flip it to 1, continue counting with count2 and reset count1. If this is not first zero, set count2 to 1. Always make sure count1 is 0 if you see 0.


Log in to reply
 

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