Вот решение для динамического программирования, которое находит минимальное значение для pos + abs(neg + pos)
(согласно обновлению OP) и печатает одно из возможных решений.Нам нужно сохранить как общую сумму, так и сумму натуральных чисел как состояние dp, чтобы найти минимум.Я не уверен, сможем ли мы решить это без измерения pos
.Сложность времени составляет O(#elements * (sum of absolute values of elements)^2)
.Конечно, если отдельные числа очень велики, это неосуществимое решение.В этом случае подход грубой силы будет работать, когда число элементов равно ~20
.
a1 = [2, 1, 1, -1]
a2 = [-1, -2, -2, -4]
memo = {} # to store dp state
nxt = {} # for reconstructing path
def foo(a1, a2, index, total, pos):
if index == len(a1):
return pos + abs(total)
if (index, total, pos) in memo:
return memo[(index, total, pos)]
# take from first array
if a1[index] > 0:
r1 = foo(a1, a2, index+1, total + a1[index], pos+a1[index])
else:
r1 = foo(a1, a2, index+1, total + a1[index], pos)
# take from second array
if a2[index] > 0:
r2 = foo(a1, a2, index+1, total + a2[index], pos+a2[index])
else:
r2 = foo(a1, a2, index+1, total + a2[index], pos)
# save path taken at this step
if r1 < r2:
nxt[index] = 0
else:
nxt[index] = 1
memo[index, total, pos] = min(r1, r2)
return min(r1, r2)
print('minimum sum:', foo(a1, a2, 0, 0, 0)) # minimum sum: 2
# path reconstruction
path = []
node = 0
while node < len(a1):
path.append(nxt[node])
node += 1
print('path:', path) # path: [1, 0, 0, 0]