Given an array of integers (with at least two elements), I need to choose at least one element of each adjacent pair of elements in the array in a way that costs me the least. Then, return the cost and elements chosen.
For example,
[50, 30, 40, 60, 10, 30, 10]
我们 Select 30作为对(50,30)和对(30,40).然后,我们 Select 40作为对(40,60)和10作为对(60,10),(10,30).最后,10对(30,10).所以我们得到了30 + 40 + 10 + 10 = 90.
另一个例子,
[60, 100, 70]
有两种可能的 Select :[60,70]或[100].但是,最优解是[100],总共100个,小于60 + 70.因此,算法应该 Select 100.
我的问题是,我只成功地编写了一个返回最低成本的代码,而没有保存使用的元素.
My Code in Python
arr = [50, 30, 40, 60, 10, 30, 10]
min_sum = [0] * len(arr)
min_sum[0] = arr[0]
min_sum[1] = arr[1]
for i in range(2, len(arr)):
choice1 = min_sum[i-1] + arr[i]
choice2 = min_sum[i-2] + arr[i]
min_sum[i] = min(choice1, choice2)
res = min(min_sum[-1], min_sum[-2])
print(res)