Two pointer solution


  • 0
    Y

    Use slow pointer s to go through all the 0s,
    and use fast pointer f to go through all the 1s ,
    check the max length each time when f reach a 0.

    public class Solution {
        public int FindMaxConsecutiveOnes(int[] nums) {
            int max=0, s=0, f=0, n=nums.Length;
            
            while(f<n){
                //move s to 1
                while(s<n && nums[s]==0) s++;
                f=s;
                //move f = 0
                while(f<n && nums[f]==1) f++;
                
                //calculate and reset s
                max=Math.Max(max, f-s);
                s=f;
            }
            return max;
        }
    }
    

Log in to reply
 

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