485. Max Consecutive Ones and Maximum consecutive one’s (or zeros) in a binary array

 

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:
 
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int maxCount = 0;
for(int i : nums){
if(i == 1){
count++;
}else{
maxCount = Math.max(maxCount,count);
count = 0;
}
}
return Math.max(count,maxCount);
}
}
 

Given a binary array arr[] consisting of only 0s and 1s, find the length of the longest contiguous sequence of either 1s or 0s in the array.

Examples : 

Input: arr[] = [0, 1, 0, 1, 1, 1, 1]
Output: 4
Explanation: The maximum number of consecutive 1’s in the array is 4 from index 3-6.

Input: arr[] = [0, 0, 1, 0, 1, 0]
Output: 2
Explanation: The maximum number of consecutive 0’s in the array is 2 from index 0-1.

Input: arr[] = [0, 0, 0, 0]
Output: 4
Explanation: The maximum number of consecutive 0’s in the array is 4.

 

class gfg{

    public int findMaxCons(int[] nums){

        int count = 1;

        int maxCount = 0;

        for(int i = 1; i<nums.length;i++){

            if(nums[i] == nums[i-1]){

                count++;

            }else{

                maxCount = Math.max(maxCount,count);

                count = 1;

            }

        return Math.max(count,maxCount); 

   }

Comments

Popular Posts