--

Photo by Antonio Batinić from Pexels

First Step To Algorithm Questions

Maximum consecutive one’s (or zeros) in a binary array

Hello everybody, after I realized I need to keep track of the algorithm questions that I have solved and understood well. I started to write this series of explanations. These are for me in the first place then I hope it can help you as well. I came across this question at the “Leet Code” in the array part.

Given a binary array, find the maximum number of consecutive 1s in this array.

e.g.

input:arr[]={1,1,0,0,1,1,1,1,0,0}

output:4

input:arr[]={1,0,1,0,0,1,1,1}

output:3

So how we can solve that kind of question let me think…

We need count 1s, we know that. Then additionally we had to visit each element of an array. Which we called a traversing the array. (Just start with the index 0 and loop while the index is less than length.)In the end, we need to have a result as well. Let’s start to write code with the given frame.

class Solution {

public int findMaxConsecutiveOnes(int[] nums,int n) {

}

}

This is what we have at first then;

Initialize count and initialize max result value then traverse the array.

class Solution {

public int findMaxConsecutiveOnes(int[] nums,int n) {

int count=0,res=0;

for(int i=0;i<nums.length;i++) — — — ->traverse array left to right

{

if(nums[i]==0) — — →if we see 0 we reset count as 0

count=0;

else — — -> if we see 1 we will increase our count

{

count++;

res=Math.max(res,count); — — →this max function accept two parameter and return the max one

}

}

return res;

}

}

It was end of the solution I hope it may help you.Have a great day!

--

--