def maxrun(A,lo=None,hi=None):
if lo is None: lo,hi = 0,len(A)-1 # start with the full range
if lo > hi: return 0 # empty sub range counts for zero
if lo == hi: return 1 # single element subrange is one
mid = (lo+hi)//2 # use value in middle of range
left = right = mid # repeated range
while left>lo and A[left-1] == A[mid]: left -= 1 # expand left
while right<hi and A[right+1] == A[mid]: right += 1 # expand right
return max(right-left+1,maxrun(A,lo,left-1),maxrun(A,right+1,hi)) # recurse
print(maxrun([1,2,3,4,4,4,3,3])) # 3
您可以从中间位置检测到一条数字条纹,将其在每一侧展开,并在该条纹的左侧和右侧的剩余值上递归
返回3条中最长的(左最长、中间条纹、右最长)
请注意,当剩余范围大于当前最佳条纹时,只需向下递归即可进一步优化
相关问题 更多 >
编程相关推荐