动态编程-最小化数组的总和

时间:2019-12-02 18:58:24

标签: python arrays algorithm dynamic-programming

我的问题是:给定一个由负整数和正整数组成的数组。给您j值跳跃,r休息。每次跳跃后,您需要休息r步。此外,即使您有跳跃的能力,也可以向前移动1步。问题是要最小化数组的总和。

示例1 r = 2, j = 2, [5, 3, -4, -2, 1, 2, 3] => -4 + -2 + 3 = -3(跳5、3,休-4,-2,跳1,2,休3)

例2 r = 2, j = 3, [90, 91, 92, -2, 3, 55, 3] => -2 + 3 + 55 + 3 = 59(跳跃90,91,92休息-2,3,55,3)


我的想法:我决定使用DP解决此问题。这是我的伪代码。

def minimalSum (MIN, array, jump, rest, steps_left_to_jump, i):
    if MIN[i] is not empty:
        return MIN[i]
    if i == len(array) - 1:
        MIN[i] = array[i]
    else:
        if steps_left_to_jump == 0:
            if i == 0:
                MIN[i] = minimalSum(MIN, array, jump, rest, rest - 1, jump)
            else:
                if i + jump + 1 < len(array):
                    MIN[i] = array[i] + minimalSum(MIN, array, jump, rest, rest - 1, i + jump + 1)
            o1 = array[i] + minimalSum(MIN, array, jump, rest, 0, i + 1)
            if MIN[i] is not None:
                if o1 < MIN[i]:
                    MIN[i] = o1
            else:
                MIN[i] = o1
        else:
            MIN[i] = array[i] + minimalSum(MIN, array, jump, rest, steps_left_to_jump - 1, i + 1)
    return MIN[i]

MIN是用于存储最佳金额的数组。

不适用于所有输入的问题,可以帮助我确定我要去哪里了。考虑例子 r = 2, j = 2 , [2 ,-2 ,-3,1 ,3 ,4]。答案应该是1(访问2,-2,跳转-3,休息4)2-2-3 + 4 = 1,但是我的程序输出5

1 个答案:

答案 0 :(得分:0)

您的问题似乎在这一行:

if i == 0:
    MIN[i] = minimalSum(MIN, array, jump, rest, rest - 1, jump)

这将阻止您在i为0时选择“访问”,因为您始终会迈出第一步。我不知道您的完整代码,但这部分应该是:

if i == 0:
    MIN[i] = min(minimalSum(MIN, array, jump, rest, rest - 1, jump) , # case where you jump at 0
                 array[0] + minimalSum(MIN, array, jump, rest, 0, 1)  # case where you visit index 0
                )

此外,如果jump>len(MIN)-1,您的代码也会给您带来越界错误。如果满足此条件,则您应该始终访问。 鉴于所有这些,我将编写递归公式,然后您可以记住它:

def opt_sum(array, r, j):
    if j > len(array)-1:
        return sum(array)  # cannot jump, return sum of full array
    else:
        visit_val = array[0] + opt_sum(array[1:], r, j)  # best sum if you choose to visit index 0
        jump_val = (
                sum(array[j:j+r])     # total mandatory resting visits
                + opt_sum(array[j+r:], r, j)  # the optimal sum of the subarray
                )                             # starting after the rest
        return min(visit_val, jump_val)  # return best of both policies