# Simple O(n) Java Solution With Explanation. O(1) space. Easy to understand

• I have used 3 variables
previous: Stores the number of one before we encounter a zero
current: stores the number of ones in current trail
result: stores the maximum of trails of ones after flipping

Basic idea is to count the number of ones before a zero and after a zero and then comparing this value with the previous result.

``````public class Solution {
public int findMaxConsecutiveOnes(int[] nums)
{
if(nums.length ==0)
return 0;
int previous = 0;
int current =0;
int result = 0;
boolean wasLastZero = false;//Checks for 2 consecutive zeroes and discards previous as this cannot be the highest length
for(int i=0; i<nums.length;i++)
{
if(nums[i]==0)
{
previous = current +1;
current =0;
if(wasLastZero)
previous = 0;
wasLastZero= true;
}
else
{
current++;
wasLastZero= false;
}
result = Math.max(result,previous+current);
}
return result;
}
}
``````

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