我们有两个带有正整数的列表。
我们需要找到一组索引S(N的子集= {1,2,3,.. n}),我们假设它是{2,3,5}。现在,我们得到一个新集合S'= N-S = {1,4}
对于S和S',需要将(sum(A [S]])^ 2 /(sum(B [S'])))最大化。
正如您所说,近似解也将起作用。我们可以使用的一种启发式方法是,我们需要选择这样的S,以使A list的值较高而B list的值为低。
当我们对A的子集求和的平方时,让我们对A进行排序,然后选择一个子列表,以便获得最高分。
import numpy as np
A = np.array([1, 2, 3, 4, 1, 2, 3])
B = np.array([3, 3, 1, 2, 1, 3, 1])
sorted_idx = sorted(range(len(A)), key=lambda k: A[k]) # also other sorting strategy can be used, A[k]/B[k]
A_p = A[sorted_idx]
B_p = B[sorted_idx]
max_s = 0
part_ans = -1
for i in range(len(A_p)):
cur_s = (sum(A_p[:i])**2)/sum(B_p[i:])
if cur_s >= max_s:
print(cur_s)
max_s = cur_s
part_ans = i
print(f'The partitions are: {sorted_idx[:i]} and {sorted_idx[i:]}')