总数集(也为负),总和等于0
我有一组庞大的数字,并有定义的顺序。用简单的术语逻辑看起来就是这样:
data ['values'] = [1,1,3,4,4,-9,10]
data ['order'] = [1,2,3,4,5,6,7]
预期= 0
预期 希望返回是我们可以用总和等于0获得的最大值子集的原始顺序和值。 对于这种情况,最佳解决方案将是
解决方案['values'] = [1,1,3,4,-9]
解决方案['order'] = [1,2,3,4,6]
该总和也可以通过用第五次替换第4阶数字来实现但是,订单编号是一个最佳解决方案就足够了。目标是达到总和= 0的最大可能大小。
正在寻找背包问题和最大子阵列算法的变化,但没有一个满足我的需求。
任何提示或指示都赞赏。
I have a huge set of numbers with a defined order. The logic in simple terms would look like this:
data['values'] = [1,1,3,4,4,-9,10]
data['order'] = [1,2,3,4,5,6,7]
ExpectedSum = 0
What I wish to return is the original order and values of biggest possible subset of values that we can get with total sum equal 0.
For this case one optimal solution would be
solution['values'] = [1,1,3,4,-9]
solution['order'] = [1,2,3,4,6]
The sum could be also achieved by replacing 4th order number with 5th order number, however, one optimal solution is enough. The goal is to reach maximum possible size of subset with total sum =0.
Was looking for variations of Knapsack problem and maximum subarray algorithms but none met my needs.
Any hints or directions appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所有固定长度的子集都可以使用“ n选择k” - 道找到。要找到最长的迭代以k = n开头,然后减少一个。
备注:要制作
id _
从1开始,只需更改枚举
如下All subsets of fixed length can be found with the "n choose k"-way. To find the longest the iteration starts with k=n and decreases by one.
Remark: to make the
id_
starting from 1, simply change theenumerate
as followenumerate(l, start=1)
也许我缺少一些东西(已经很晚了),但是如果我们用
k
元素表示子集,则为s(k)
,并且我们有n
总共可以:您可以:s(n)
是否总和为0;如果是这样,那是最大的子集s(n-1)
是否总和为0; 如果没有,则有n
这样的集合s(n-2)
dim dim;有n*(n-1)
这样的集合等。这是一种“蛮力”解决方案,可能远非最佳,但是如果最大的子集有望相对较大(大小接近
n
),那就不错了。请注意,每个步骤都可以利用前面步骤中计算的总和。您的
解决方案[order]
似乎是解决方案子集的索引。当然可以做到这一点,但是我不确定为什么您需要获得值及其索引?有点多余。最后,尽管在纯Python中可行,但Numpy库可能对这种问题有用。
Maybe I'm missing something (it's getting late), but if we denote a subset with
k
elements asS(k)
and we haveN
elements in total, you could:S(N)
sums to 0; if so, that's the largest subsetS(N-1)
sums to 0; there areN
such setsS(N-2)
does; there areN*(N-1)
such setsand so on. This is a "brute force" solution and probably far from optimal, but if the largest subset is expected to be relatively large (close to
N
in size) it shouldn't be too bad. Note that each step can utilize the sums computed in the preceding step.Your
solution[order]
seems to be the indices to the solution subset. It can be done of course, but I'm not sure why you need to get both the values and their indices? It's kind of redundant.Finally, while doable in pure Python, the NumPy library might be useful for this kind of problem.