Python 函数,该函数返回具有条件的最大子数组的长度
一个0和1的数组被提供给输入。必须实现一个函数,该函数返回零和一的数目匹配的最大子序列的长度。序列示例:[0,0,1,0,1,1,1,0,0,0]。在从1(索引从0)到8的数组切片中,0的数量等于1的数量,子数组的长度为8。 下面的代码部分解决了任务,解决了大多数测试,但不是全部测试Python 函数,该函数返回具有条件的最大子数组的长度,python,algorithm,Python,Algorithm,一个0和1的数组被提供给输入。必须实现一个函数,该函数返回零和一的数目匹配的最大子序列的长度。序列示例:[0,0,1,0,1,1,1,0,0,0]。在从1(索引从0)到8的数组切片中,0的数量等于1的数量,子数组的长度为8。 下面的代码部分解决了任务,解决了大多数测试,但不是全部测试 def longest_subsequence(arr): hash_table = {} k = 0 max_ = 0 temp = None for idx, el in
def longest_subsequence(arr):
hash_table = {}
k = 0
max_ = 0
temp = None
for idx, el in enumerate(arr):
if el == 0:
k += 1
else:
k -= 1
if k not in hash_table:
hash_table[k] = idx
if k in hash_table:
temp = idx - hash_table[k]
if temp > max_:
max_ = temp
return max_
def longest_subsequence(arr):
hash_table = {0:-1}
k = 0
max_ = 0
temp = None
for idx, el in enumerate(arr):
if el == 0:
k += 1
else:
k -= 1
if k not in hash_table:
hash_table[k] = idx
if k in hash_table:
temp = idx - hash_table[k]
if temp > max_:
max_ = temp
return max_