# My Java Solution. O(n) time and O(1) space.

• ``````class Solution {
/*
If this is the first number 1 or the number of the current consecutive zeros is larger than 1,
then the number of previous number 1's is either zero or should be ignored (Because at most one 0 can be negated)
If the number of the current consecutive zeros is exactly one,
then the previous consecutive ones is connected to the coming consecutive ones by negating the current zero
*/
public int findMaxConsecutiveOnes(int[] nums) {
if(nums == null) {
return 0;
} else {
int curOnes = 0, preOnes = 0, zeros, maxLen = 1;

for(int idx = 0; idx < nums.length; ) {
if(nums[ idx ] == 1) {
for(; idx<nums.length && nums[ idx ]==1; idx++, curOnes++);
maxLen = Math.max(maxLen, curOnes+preOnes);
} else {
for(zeros = 0; idx<nums.length && nums[ idx ]==0; idx++, zeros++);
preOnes = zeros==1?curOnes+1:0;
maxLen = Math.max(maxLen, curOnes+1);
curOnes = 0;
}
}

return maxLen;
}
}
}
``````

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