1

Suppose I have a list of 10 elements [a, b, c, d, e, f, g, h, i, j] and I can multiply each element by 0, 1, 2, -1, -2.

The total of the multiplication factors I use must be equal to zero. Ie if I multiply five numbers by -1 I must multiply the other five by 1, or I can multiply a by 2, b and c by -1 and the rest by 0.

I want to find the list resulting from this operation that has the largest sum.

How can I go about coding this in python?

I've tried coding every single iteration of [2, 1, 0, -1, -2] and deleting the lists that do not add to 0 and then multiplying by the original list, however I got stuck.

  • 3
    Can you share your iteration approach? Hint: when would such sum be maximal. – Willem Van Onsem Aug 11 '19 at 20:48
  • 1
    `I can multiply each element by 0, 1, 2.` and `if I multiply five numbers by -1` These two statements conflict, is one a typo? Do you mean `2, -1, 0, 1, 2`? – Mark Aug 11 '19 at 20:52

1 Answers1

1

You can sort the list, scan it from the ends towards the center, assigning 2 to the larger element and -2 to the smaller.

def baby_knapsack(xs):
    xs = sorted(xs, reverse=True)
    res =  list()
    n = len(xs)
    for i in range(n//2):
        res.extend(((xs[i], 2), (xs[-1-i], -2)))
    if n % 2 == 1:
        res.append((xs[n//2], 0))
    return res

xs = [-10, -5, 0, 5, 10, 15]

# In [73]: q.baby_knapsack(q.xs)                                           
# Out[73]: [(15, 2), (-10, -2), (10, 2), (-5, -2), (5, 2), (0, -2)]
hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51