# Two Java O(n) solutions

• This is my original code. The basic idea is using two indices to find the first 1 and the further consecutive 1.

``````    public int findMaxConsecutiveOnes(int[] nums) {
int first = 0; int second = 1;
int max = 0;
while(first < nums.length){
if(nums[first] == 0){
first++;
continue;
}
second = first + 1;
while(second < nums.length){
if(nums[second] == 1){
second++;
}else{
break;
}
}
max = max > second - first ? max : second - first;
first = second + 1;
}
return max;
}
``````

The second solution is inspired from other's solution. The basic idea is to compare the curCount of 1s to the existing max. When encountering a 0, curCount will start from 0 again.

``````    public int findMaxConsecutiveOnes(int[] nums) {
int curCount = 0; int max = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 1){
curCount++;
max = max > curCount ? max : curCount;
}else{
curCount = 0;
}
}
return max;
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.