O(1) solution solving data stream


  • 0

    Denote j to be the left window side, denote k to be the position of last 0. When iterating and meeting a 0, update j and k.

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int j=0;
            int k=-1;
            int max=0;
            
            for(int i=0;i<nums.length;i++){
                if(nums[i]==0){
                    if(k!=-1){
                        j=k+1;
                    }
                    k=i;
                }
                max=Math.max(i-j+1,max);
            }
            
            return max;
        }
    }

Log in to reply
 

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