0

Max Consecutive Ones

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: