最大总和子阵列 - 返回子阵列和总和 - 分而治之

时间:2017-01-23 20:17:02

标签: python algorithm recursion divide-and-conquer

我需要返回使用除法和征服方法的最大和子数组算法的和和子数组。

我能够在所有测试中正确计算总和。但是,我无法计算正确的子阵列。

class Results:
    max = 0
    maxSubArray = []
    start_index = 0
    stop_index = 0

def divide_and_conquer(arr, left, right):
    res = Results()

    maxLeftBorderSum = 0
    maxRightBorderSum = 0
    leftBorderSum = 0
    rightBorderSum = 0
    center = (left + right)//2

    if left == right:
        if(arr[left]>0):
            res.max = arr[left]
            res.start_index = left
            res.stop_index = right
            res.maxSubArray = arr[left:right]
            return res
        else:
            res.max = 0
            res.start_index = left
            res.stop_index = right
            res.maxSubArray = arr[:]
            return res

    maxLeft = divide_and_conquer(arr, left, center)
    maxRight = divide_and_conquer(arr, center+1, right)

    maxLeftSum = maxLeft.max
    maxRightSum = maxRight.max

    rightstopindex = 0
    leftstartindex = 0

    for i in range(center, left-1, -1):
        leftBorderSum = leftBorderSum + arr[i]
        if leftBorderSum > maxLeftBorderSum:
            maxLeftBorderSum = leftBorderSum
            leftstartindex = i

    for i in range(center+1, right+1):
        rightBorderSum = rightBorderSum + arr[i]
        if rightBorderSum > maxRightBorderSum:
            maxRightBorderSum = rightBorderSum
            rightstopindex = i

    res.max = max(maxLeftBorderSum + maxRightBorderSum, max(maxRightSum, maxLeftSum))

    if res.max == maxLeftBorderSum + maxRightBorderSum:
        res.start_index = leftstartindex
        res.stop_index = rightstopindex
        res.maxSubArray = arr[leftstartindex:rightstopindex]
    elif res.max == maxRightSum:
        res.start_index = maxRight.start_index
        res.stop_index = maxRight.stop_index
        res.maxSubArray = arr[maxRight.start_index:maxLeft.stop_index]
    else:
        res.start_index = maxLeft.start_index
        res.stop_index = maxLeft.stop_index
        res.maxSubArray = arr[maxLeft.start_index:maxLeft.stop_index]

    return res

示例输出

阵列:1 4 -9 8 1 3 3 1 -1 -4 -6 2 8 19 -10 -11

正确的子阵列:8 1 3 3 1 -1 -4 -6 2 8 19

我的结果:[8,1,3,3,1,-1,-4,-6,2,8]

我的总和(正确):34

阵列:2 9 8 6 5 -11 9 -11 7 5 -1 -8 -3 7 -2

正确的子阵列:2 9 8 6 5

我的结果:[2,9,8,6]

我的总和(正确):30

阵列:10 -11 -1 -9 33 -45 23 24 -1 -7 -8 19

正确的子阵列:23 24 -1 -7 -8 19

我的子阵:[10,-11,-1,-9,33,-45,23,24,-1,-7,-8]

我的总和(正确):50

阵列:31 -41 59 26 -53 58 97 -93 -23 84

正确的子阵列:59 26 -53 58 97

我的子阵:[59,26,-53,58]

我的总和(正确):187

阵列:3 2 1 1 -8 1 1 2 3

正确的子阵列3 2 1 1

我的子阵列[3,2,1,1,-8,1,1,2]

我的总和(正确)7

阵列:12 99 99 -99 -27 0 0 0 -3 10

正确的子阵列:12 99 99

我的子阵列[]

我的总和(正确)210

数组:-2 1 -3 4 -1 2 1 -5 4

正确的子阵列4 -1 2 1

我的子阵列[4,-1,2]

我的总和(正确)6

1 个答案:

答案 0 :(得分:1)

以下变量需要以不同方式初始化。因为它们在上面的代码中被置为零,所以当数组只包含负数时,它们在循环中永远不会被更改。

maxLeftBorderSum = arr[center]
maxRightBorderSum = arr[center+1]
leftstartindex = center
rightstopindex = center+1
相关问题