001 Max Consecutive Ones
Given a binary array, find the maximum number of consecutive 1s in this array.
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
and1
.The length of the input array is a positive integer and will not exceed 10,000.
Solution
Code
public class Solution{
public int FindMaxConsecutiveOnes(int[] nums){
int result = 0;//number for output
int counter = 0;//number for counting
int length = nums.Length;//get the capacity of array
for(int i=0; i<length; i++){
if(nums[i]==0){
counter=0;//when value=0 reset counter
}
else{
counter++;//wen value =1, then counter +1ï¼›
result = Math.Max(result,counter);//get the bigger one between result and conterï¼›
}
}
return result;
}
}
Traverse array from left to right. If we see a 1, we increment the counter and compare it with the maximum so far. If we see a 0, we reset the counter as 0.
Last updated
Was this helpful?