简体   繁体   English

带有替代符号的不相交的maxsubarray

[英]Disjoint maxsubarray with alternate signs

i would like to find an algorithm to find the max disjoint subarray with alternated signs (not necessarily contiguos), for example in (2, -3, 4., 5, -4, 3, -3, 5, -2, 1) it returns 7 that is the greatest sum, and the subarray is (5,-3,5) 我想找到一种算法来查找具有交替符号(不一定是重叠的)的最大不相交子数组,例如在(2,-3,4.,5,-4,3,-3,5,-2,1 )返回最大和为7的子数组为(5,-3,5)

I tried something like this using dp: 我尝试使用dp这样的事情:

    A=[2,-3,4,5,-4,3,-3,5,-2,1]

    m = A[0]
    flag = A[0]    #flag has the same sign of the previously taken element
    maximum = m    #temporary maxsum

    for i in range(1,10):
        if A[i]>0 and flag<0 or A[i]<0 and flag>0: #i look only for alternate signs
             m = max(m ,A[i]+m)
             if m > maximum:
                   flag = -flag
                    maximum = m
             else:
                   if A[i]>maximum:
                   maximum=A[i]
                   flag=-flag


     print(maximum)

it gives 7 but it's only a coincidence 它给出7,但这只是一个巧合

Should i have to use another For nested in order to properly compare every possible subarray? 我是否应该使用另一个For嵌套以正确比较每个可能的子数组?

A=[2,-3,4,5,-4,3,-3,5,-2,1]
dp = [[([], 0), ([], 0)]]
for i, x in enumerate(A):
    curr = list(dp[-1])
    if x < 0 and curr[0][1] + x > curr[1][1]:
        curr[1] = (curr[0][0] + [i], curr[0][1] + x)
    elif x > 0 and curr[1][1] + x > curr[0][1]:
        curr[0] = (curr[1][0] + [i], curr[1][1] + x)
    dp.append(curr)

print dp[-1][0]

This will print a tuple with the indices of the elements to take, and the maximum sum. 这将打印一个元组,其中包含要获取的元素的索引以及最大和。

Each element in dp represents the best solution up to that point in the list for the case where the next number needs to be positive (first element) and where the next number needs to be negative (second element). 对于下一个数字需要为正数(第一个元素)而下一个数字需要为负数(第二个元素)的情况, dp每个元素代表列表中到目前为止的最佳解决方案。 Within each of those best solutions, we a list of indices to get to that point, and the maximum sum. 在每个最佳解决方案中,我们列出了达到该点的索引以及最大和。 The answer is always going to be from the last element in dp where the most recently taken number was positive. 答案永远是从dp中的最后一个元素开始的,最近的数字是肯定的。

If you don't need to track the elements used: 如果您不需要跟踪使用的元素:

A=[2,-3,4,5,-4,3,-3,5,-2,1]
dp = [[0, 0]]
for i, x in enumerate(A):
    curr = list(dp[-1])
    if x < 0 and curr[0] + x > curr[1]:
        curr[1] = curr[0] + x
    elif x > 0 and curr[1] + x > curr[0]:
        curr[0] = curr[1] + x
    dp.append(curr)

print dp[-1][0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM