给定一个仅包含零和一的数组,找到零的索引,如果将其转换为一,将形成最长的一序列。
例如,给定数组:
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1]
替换索引 10 处的零(从 0 开始计数)形成 9 个 1 的序列:
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1] '------------^------------'
您的任务是完成确定在哪里用 1 替换 0 以获得最大长度子序列的函数。
备注:
- 如果有多个结果,则返回最后一个:
[1, 1, 0, 1, 1, 0, 1, 1] ==> 5
- 数组将始终只包含零和一。
你能一次性完成这个吗?
如何通过这个条件?有几个测试用例。我通过了其中的88个 但无法通过 1922 个以上的测试用例。
问题链接如下:
https://www.codewars.com/kata/5a00a8b5ffe75f8888000080/train/python
def findIndex(arr):
mlen = 0
mindex = -1
curr = 0
prev = -1
for i in range(len(arr)):
if arr[i] == 1:
curr += 1
else:
if prev != -1:
curr = i - prev
prev = i
if curr > mlen :
mlen = curr
mindex = prev
return mindex