Two pointer solution

  • 0

    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;
                //move s to 1
                while(s<n && nums[s]==0) s++;
                //move f = 0
                while(f<n && nums[f]==1) f++;
                //calculate and reset s
                max=Math.Max(max, f-s);
            return max;

Log in to reply

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