I have a dictionary of length n choose m, with keys of tuples of length m containing all combinations of integers 1 to n. I would like to compute the maximum sum of the values of this dictionary such that the indices of the tuple keys are unique, storing the combinations that make up this maximum.
Example input:
input_dict = {
(1, 2): 16,
(1, 3): 4,
(1, 4): 13,
(1, 5): 8,
(1, 6): 9,
(2, 3): 6,
(2, 4): 19,
(2, 5): 7,
(2, 6): 16,
(3, 4): 12,
(3, 5): 23,
(3, 6): 12,
(4, 5): 17,
(4, 6): 19,
(5, 6): 21
}
Example output:
(((1, 2), (3, 5), (4, 6)), 58)
My current approach: compute the sum of all unique combinations of outputs and take the maximum.
gen_results = [{}]
for (key, val) in input_dict.items():
gen_results[0][(key,)] = val
i = 0
complete = False
while not complete:
complete = True
gen_results.append({})
for (combinations, running_sum) in gen_results[i].items():
for (key, val) in input_dict.items():
unique_combination = True
for combination in combinations:
for idx in key:
if idx in combination:
unique_combination = False
break
if not unique_combination:
break
if unique_combination:
complete = False
gen_results[i+1][combinations + (key,)] = running_sum + val
i += 1
generation_maximums = []
for gen_result in gen_results:
if gen_result == {}:
continue
generation_maximums.append(max(gen_result.items(), key=(lambda x: x[1])))
print(max(generation_maximums, key=(lambda x: x[1])))
How can I improve my algorithm for large n and m?