Home ยป Max Consecutive Ones – C# Program

Max Consecutive Ones – C# Program

Given a binary array nums, return the maximum number of consecutive 1‘s in the array.

Example 1:

Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.

Example 2:
Input: nums = [1,0,1,1,0,1] Output: 2

Solution 1:

 public int FindMaxConsecutiveOnes(int[] nums) {
        int maxCount=0;
        int minCount=0;
        for(int i=0;i<nums.Length;i++){
            if(nums[i]==1){
                minCount++;
            }
            else{
                minCount=0;
            }
            
            if(minCount>maxCount){
                maxCount=minCount;
            }
        }
        return maxCount;
        
    }

Solution 2:

 public int FindMaxConsecutiveOnes(int[] nums) {
        int maxCount=0,minCount=0;
        foreach(var item in nums){
             maxCount=Math.Max(maxCount,minCount=item==0 ? 0: minCount+1);
        }
        return maxCount;
 }

Need help?

Read this post again, if you have any confusion, or else add your questions to Community