算法看起来正确,无法找出错误的位置。从8到10的代码返回是最大子数,总共为32.但实际答案是8到11,总共43。
import sys
import math
def maxtuple(lss,rss):
if lss[2] > rss[2]:
return lss
else:
return rss
def crosssubarray(A, start, mid, end):
ls=rs=-sys.maxsize
maxleft=0
maxright=0
sum = 0;
for i in reversed(range(start, mid)):
sum = sum + A[i]
print(i)
if sum > ls:
ls = sum
maxleft = i
sum = 0
for i in range(mid+1, end):
sum = sum+ A[i]
if sum > rs:
rs = sum
maxright = i
return (maxleft, maxright, ls+rs)
def maxsubarray(A,start,end):
if start == end:
return (start,end,A[start])
else:
mid = (start+end)/2
lss = maxsubarray(A, start, mid)
rss = maxsubarray(A, mid+1, end)
css = crosssubarray(A, start, mid, end)
maxsub = maxtuple(lss,rss)
maxall = maxtuple(maxsub, css)
return maxall`enter code here`
A = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(maxsubarray(A,0,15))
答案 0 :(得分:1)
问题是范围(开始,中间)产生开始,开始+ 1,...,中间1但不包括中间。
这意味着您的crosssubarray不包含中间值。
而是尝试:
for i in reversed(range(start, mid+1)):