Find the Longest Streak of 1's in a Binary Array using Java Code

 


You have been given an Integer Array which contains only 1s and 0s, and asked to find the longest running streak of 0 or 1 in the array. Sound familiar? Its a common interview question. Let's try to find a solution using Java. 

We would required two counters here, 1 counter to keep track of the running count, and the second one to keep track of the maximum running streak found. 

We'll loop through the array using a for loop. 

Here is the code for your reference:


/**
 * Find the longest Streak of 1s
 * @author computengine.com
 * @param a
 * @return the length of the longest streak
 */
public int findLongestStreak(int[] b) {
	
	System.out.println("Array for processing: "+Arrays.toString(b));
	
	int count=0,max=0;
	
	//loop through the array
	for(int i=0;i<b.length;i++) {
		//increment count when 1 is found
		if(b[i]==1)
			count+=1;
		//if count is greater than previous max streak, replace max
		if(count>max)
			max=count;
		//reset counter if 0 is found
		if(b[i]==0)
			count=0;			
	}
	
	System.out.println("Max Repeating Streak of 1s: "+max);
	
	return max;
}


As you can see, we are replacing the max counter if a bigger streak is found. This will help us keep the max number as the latest. Also, we are resetting the count tracker as soon as 0 is found. 

//if count is greater than previous max streak, replace max
if(count>max)
	max=count;
//reset counter if 0 is found
if(b[i]==0)
    count=0;

In this example, we are trying to find the streak of 1s. You can make few changes to the code and modify it to find the streak of 0s, or any number or character for that matter.

Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on FacebookTwitterTumblr. 

Comments

Popular posts from this blog

Calculate Your CTC Salary Hike Percentage - Online Calculator to find your New Salary

Java Program to read Excel File and Load into Array

Java Program to Read a Properties file and return a Property Value

4 ways to add New Line Character to a String in Java