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
Approach
To solve this problem we can iterate through the indices in the array in two nested while loop by following algorithm:
- Create a variable maximum which will store the updated maximum consecutive 1s during traversing.
- Create and initialize a variable i with first index.
- Now run a while loop until i < array size.
- Inside the loop we will check if number at current index i is 1 or not. If it is not equal to 1 then simply increment the index i. Else if it is equal to 1, then run a nested while loop by creating a count variable and initialize with 0. Then traverse the array for consecutive 1s in that nested while loop. i.e. traverse array while num[i] is equal to 1, along with keep incrementing the count of current consecutive 1s as shown in figure below:
- After encountering 0 or end of the array, update the maximum variable by comparing its old value with current consecutive 1s count stored in count variable.
- After while loop completes return the maximum value.
int findMaxConsecutiveOnes(int* nums, int numsSize){
int maximum=0;
int i=0;
while(i<numsSize){
int conOnes=0;
while(i<numsSize&&nums[i]==1){
conOnes++;
i++;
}
if(conOnes>maximum){
maximum=conOnes;
}
i++;
}
return maximum;
}
int findMaxConsecutiveOnes(int* nums, int numsSize){
int maximum=0;
int i=0;
int conOnes=0;
while(i<numsSize){
if(nums[i]!=0){
conOnes++;
i++;
}
else{
conOnes=0;
i++;
}
if(conOnes>maximum)
maximum=conOnes;
}
return maximum;
}