Wednesday, June 7, 2017

Max consecutive ones


Problem Statement

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

Link to GitHub :Code


Example 1:
Input: [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.
Note:
  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000
110111
^ maxHere = 1

110111
.^ maxHere = 2

110111
..^ maxHere = 0

110111
...^ maxHere = 1

110111
....^ maxHere = 2

110111
.....^ maxHere = 3


public class MaxConsecutiveOnes {
 
  public static int get(int [] arr)
  {
   int maxNow=0,max=0;
   
   //loop through the array to find the maximum no of consecutive arrays
   for( int i :arr)
   {
    //Reset MaxNow to 0 or else increment by one
    max=Math.max(max,maxNow= i==0 ?0 :maxNow+1) ;
   }
  
   return max;
  }
}

No comments:

Post a Comment