在给定索引约束的情况下,查找多个数组的最大总和的最佳方法



>假设我有 3 个排序数组,每个数组长度为 4,我想从每个数组中选择一个索引,使索引的总和等于 4。如何在不测试所有可能选择的情况下找到最大可能的总和?

例如,我有以下数组

1 : [0,0,0,8]
2 : [1,4,5,6]
3 : [1,5,5,5]
Then the solution would be 3,0,1. Because 3 + 0 + 1 = 4 and 8 + 1 + 5 is 
the maximum combination where the sum of the indexes are 4.

我需要一个可以推广到 n 个大小为 m 的数组的解决方案,其中索引的总和可以等于任何东西。

例如,可以要求使用1000个数组

来解决该问题,这些数组的大小均为1000,其中索引的总和为2000。

如果某处有一个 python 包可以做到这一点,请告诉我。

这将实现它,不确定速度是否满足您的要求

df1=pd.DataFrame([[0,0,0,8],[1,4,5,6],[1,5,5,5]])
import functools    
df=pd.DataFrame(list(itertools.product([0,1,2,3],[0,1,2,3],[0,1,2,3])))
df=df.loc[df.sum(1)<=4,:]
df.index=df.apply(tuple,1)
df.apply(lambda x : df1.lookup(df.columns.tolist(),list(x.name)),1).sum(1).idxmax()

Out[751]: (3, 0, 1)
df.apply(lambda x : df1.lookup(df.columns.tolist(),list(x.name)),1).sum(1).max()
Out[752]: 14

最新更新