查找要被1替换的0的索引以获得二进制数组中最长的1的连续序列-Python中的Set-2
假设我们有一个二进制数组。我们必须找到0的位置,可以将其替换为1,以获取最大连续序列数1s。
因此,如果输入类似于[1,1,0,0,1,0,1,1,1,1,1,0,1,1],则输出将为10,因此数组将为[1,1,0,0,1,0,1,1,1,1,1,1,1]。
为了解决这个问题,我们将遵循以下步骤-
我:=0,
n:=A的大小
count_left:=0,count_right:=0
max_i:=-1,last_i:=-1
count_max:=0
当我<n时
如果last_i与-1不同,则
last_i:=我
count_left:=count_right
count_right:=0
count_max:=count_left+count_right+1
max_i:=last_i
如果count_right+count_left+1>count_max,则
count_right:=count_right+1
如果A[i]与1相同,则
除此以外,
我:=我+1
如果last_i与-1不同,则
count_max:=count_left+count_right+1
max_i:=last_i
如果count_left+count_right+1>count_max,则
返回max_i
示例
让我们看下面的实现以更好地理解-
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))
输入值
[1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1]
输出结果
10