Traverse the whole array. Keep a count
in the following way:
Do
+1
for every 0 bit encountered.Do
-1
for every 1.
If this count reaches -ve at any stage, reset it to 0. Keep track of max
value of this count
. Add this max_count
to number of 1's
in input array. This will be your answer.
Code:
arr = [1, 0, 0, 1, 0, 0, 1, 0]# I'm taking your sample case. Take the input the way you wantcount,count_max,ones = 0,0,0for i in arr: if i == 1: ones += 1 count -= 1 if i == 0: count += 1 if count_max < count: count_max = count if count < 0: count = 0print (ones + count_max)
Small and simple :)