【问题标题】:Finding max sum sub list and sum with divide and conquer通过分而治之查找最大总和子列表和总和
【发布时间】:2018-03-18 21:47:45
【问题描述】:

所以我正在尝试打印最大总和及其相应的子列表,但我无法弄清楚如何获取其子列表。到目前为止,这是我使用 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)

【问题讨论】:

  • 任何示例 i/p 和预期的 o/p?
  • 输入:[7,-1,1,2,-8,1] 输出:9 [7 -1 1 2]
  • 嗨@catpuccino,请编辑您的代码,使其更清晰。 strsddleSum 中的某些内容:是否是函数的 for 循环部分。如果是,请适当缩进代码。另一方面,在 sumHelper 中,你有全局索引,但是你在任何函数中都不用它做任何事情。如果是这样的话,最好把它拉出来。即使您正在操作索引,更明智的方法是将其作为参数传递给需要它的函数。

标签: python algorithm divide-and-conquer


【解决方案1】:

您只返回一个范围的总和。要获得范围,只需返回一个 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)

【讨论】:

    猜你喜欢
    • 2017-06-08
    • 2019-02-08
    • 2017-06-07
    • 2020-03-30
    • 2013-02-10
    • 2011-02-15
    • 2014-01-07
    • 2018-12-27
    • 1970-01-01
    相关资源
    最近更新 更多