# Find Indexs of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array - Set-2 in Python

Suppose we have one binary array. We have to find the position of 0 that can be replaced with 1 to get maximum number of continuous sequence of 1s.

So, if the input is like [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1], then the output will be 10, so the array will be [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1].

To solve this, we will follow these steps −

• i := 0,

• n := size of A

• count_left := 0, count_right := 0

• max_i := -1, last_i := -1

• count_max := 0

• while i < n, do

• if A[i] is same as 1, then

• count_right := count_right + 1

• otherwise,

• if last_i is not same as -1, then

• if count_right + count_left + 1 > count_max, then

• count_max := count_left + count_right + 1

• max_i := last_i

• last_i := i

• count_left := count_right

• count_right := 0

• i := i + 1

• if last_i is not same as -1, then

• if count_left + count_right + 1 > count_max, then

• count_max := count_left + count_right + 1

• max_i := last_i

• return max_i

## Example

Let us see the following implementation to get better understanding −

Live Demo

def find_max_one_index(A):
i = 0
n = len(A)
count_left = 0
count_right = 0
max_i = -1
last_i = -1
count_max = 0
while i < n:
if A[i] == 1:
count_right += 1
else:
if last_i != -1:
if count_right + count_left + 1 > count_max:
count_max = count_left + count_right + 1
max_i = last_i
last_i = i
count_left = count_right
count_right = 0
i += 1
if last_i != -1:
if count_left + count_right + 1 > count_max:
count_max = count_left + count_right + 1
max_i = last_i
return max_i
A = [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1]
print(find_max_one_index(A))

## Input

[1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1]

## Output

10

Updated on: 25-Aug-2020

231 Views

##### Kickstart Your Career

Get certified by completing the course