找到最大和子子列表并用除法和征服求和

时间:2017-10-07 04:37:24

标签: python algorithm divide-and-conquer

所以我试图打印最大总和以及相应的子列表,但我很难弄清楚如何获取其子列表。到目前为止,我的代码使用的python只返回最大值:

full = [7,-1,1,2,-8,1]
indices = []

def sumHelper(listnum, a, z):
    if a == z:
        global indices
        return listnum[a]
    mid = (a+z)//2
    return max(sumHelper(listnum,a,mid),sumHelper(listnum,mid+1,z),straddleSum(listnum,a,mid,z))


def straddleSum(listnum, a, m, z):
    right = -(2**31)-1
    left = -(2**31)-1
    count = 0
    for i in range(m,a-1,-1):
        count = count + listnum[i]
        if count > left:
            left = count

    count = 0
    for i in range(m+1,z+1):
        count = count + listnum[i]
        if count > right:
            right = count

    return right + left

print(sumHelper(full, 0, len(full)-1))
print(indices)

1 个答案:

答案 0 :(得分:2)

您只返回范围的总和。要获得范围,只需返回一个sum和range的元组,而不仅仅是总和:return listnum[a], (a,z)。然后给max一个关键函数,这样它只使用元组中的和来找到最大范围key= lambda x: x[0]

full = [7,-1,1,2,-8,1]
# full = [-1,-2,-3,-4]
# full = [1,2,-100,3,4]
indices = []

def sumHelper(listnum, a, z):
    if a == z:
        global indices

        # return sum of range and it's left and right index
        return listnum[a], (a,z)
    mid = (a+z)//2
    return max(sumHelper(listnum,a,mid),sumHelper(listnum,mid+1,z),straddleSum(listnum,a,mid,z), key= lambda x: x[0])


def straddleSum(listnum, a, m, z):
    right = -(2**31)-1
    left = -(2**31)-1

    lpos = rpos= None   # left and right index of max range

    count = 0
    for i in range(m,a-1,-1):
        count = count + listnum[i]
        if count > left:
            left = count
            lpos = i

    count = 0
    for i in range(m+1,z+1):
        count = count + listnum[i]
        if count > right:
            right = count
            rpos = i

    # return sum of range and it's left and right index
    return right + left, (lpos, rpos)

msum, msumb_range = sumHelper(full, 0, len(full)-1)
print(msum)
print(msumb_range)