Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找数组中非连续所有格元素最大和的逻辑实现_Python_Algorithm_Logic - Fatal编程技术网

Python 查找数组中非连续所有格元素最大和的逻辑实现

Python 查找数组中非连续所有格元素最大和的逻辑实现,python,algorithm,logic,Python,Algorithm,Logic,它们是一个包含正整数和负整数的数组 假设:1,2,-1,3,5,1,-4,2,7 现在我必须找到所有组合的最大和 组合应该是这样的 1。主集合中没有连续的元素 2.元素应为正值 起初,我想通过将其划分为偶数和赔率来实现这一点,但实际上这并没有解决问题 ods=[] evns=[] ok=0; ek=1; for x in range(n): print(str(x)+"-"+str(ok)+"-"+str(ek)) if x == ok

它们是一个包含正整数和负整数的数组 假设:1,2,-1,3,5,1,-4,2,7 现在我必须找到所有组合的最大和

组合应该是这样的

1。主集合中没有连续的元素
2.元素应为正值

起初,我想通过将其划分为偶数和赔率来实现这一点,但实际上这并没有解决问题

 ods=[]
 evns=[]
 ok=0;
 ek=1;
 for x in range(n):
            print(str(x)+"-"+str(ok)+"-"+str(ek))
            if x == ok and tkts[x]>0:
                ods.append(tkts[x])
                ok+=2
            elif x == ok and tkts[x] <= 0:
                ok+=1

            if x == ek and tkts[x]>0:
                evns.append(tkts[x])
                ek+=2
            elif x == ek and tkts[x] <= 0:
                ek+=1 
ods=[]
evns=[]
ok=0;
ek=1;
对于范围(n)内的x:
打印(str(x)+“-”+str(ok)+“-”+str(ek))
如果x==正常且tkts[x]>0:
ods.append(tkts[x])
正常+=2
elif x==正常,tkts[x]0:
evns.append(tkts[x])
ek+=2

elif x==ek和tkts[x]您可以使用DP。递归思想如下

get_max(index):
    max = 0
    for i from index+2 to len:
        if(array[i] > 0)
            v = get_max(i)
            if (v > max) max = v
    return array[index]+max
get_max(0)
如果我们回忆录

x = [1,2,-1,3,5,1,-4,2,7]
dp = [0]*len(x)
ret = 0
for i in range(len(x)-3, -1, -1):
    max = 0
    for j in range(i+2, len(x)):
        if x[j] > 0 and dp[j]>max: max = dp[j]
    if x[i] > 0:
        dp[i] = max + x[i]
        if ret < dp[i]: ret = dp[i]
x=[1,2,-1,3,5,1,-4,2,7]
dp=[0]*len(x)
ret=0
对于范围内的i(len(x)-3,-1,-1):
最大值=0
对于范围(i+2,len(x))内的j:
如果x[j]>0且dp[j]>max:max=dp[j]
如果x[i]>0:
dp[i]=max+x[i]
如果ret
(我没有测试这段代码,这只是为了这个想法)