**Problem statement:** (Leetcode problem no:487)

Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0.

**Example:**

**Input:**[1,0,1,1,0]

**Output:**4

**Description:**Flip the first 0 will get maximum 4 consecutive 1s. If second 0 is flipped still we will get 4 consecutive 1s, as at the max one 0 flip is allowed.

**Logic:**

Maintain two pointers ‘low’ to keep track of start of 1s consecutive sequence and ‘zeroIndex’ pointer to mark index at which 0 is present. Whenever we encounter next 0 we will check if current length of consecutive 1s is more than previous if yes, we will update max length else max length remains same and we will update ‘low’ to mark start of next sequence of consecutive 1s.

**Code:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public int findMaxConsecutiveOnes(int[] nums) { int low = 0,zeroIndex = -1,max = 0,i=0; for(i =0; i< nums.length;i++) { if(nums[i] == 0) { if(zeroIndex != -1) { int len = i - low; max = Math.max(max,len); low = zeroIndex+1; zeroIndex = i; } else zeroIndex = i; } } return Math.max(max,i-low); } |