O(n) suggestion, by induction. Hmm, I read the wiki now and I found out it counts as dynamic programming. Really a broad term. I had a different understanding of dynamic programming before.
Glossary
We have N
coins in N
places. Coin values are a[i]
, where 0 <= i < N
. Each coin may be selected or deselected which we express as the sequence of 0
and 1
.
Algorithm description
00
is invalid sequence in any place, because it would violate the problem constraints. 111
is also invalid because it is not optimal, 101
is always better.
Sequentially for every place i
we calculate 3 best sums, for 3 codes: 01
, 10
, 11
. The code comes from the setting of last 2 coins, that is i-1
and i
. So we have best (minimum) sums in variables b01
, b02
, b11
.
We have to start from something sure, so we will apply the algorithm 2 times. One for coin at place 0 set, and one for unset.
At the beginning we try places 0
and 1
and initiate b
s directly. b01 = a[1]
, b10 = a[0]
, b11 = a[0] + a[1]
. However if this is the round in which we choose the first coin to be unset, we can accept only b01
solution. So we assign a big number to b10
and b11
. These solutions will be quickly dropped by next algorithm steps. On the second round we will do the opposite: assign big nuber to b01
, because first bit must be set.
At step i
we have best sums for place i-1
in b
s. We compute c
s which are the best sums for place i
.
c01 = b10 + a[i] // 101 (10 -> 01)
c10 = min(b01, b11) // 010 (01 -> 10) or 110 (11 -> 10)
c11 = b01 + a[i] // 011 (01 -> 11)
That comes from following possibilities:
010 - b01 -> c10
011 - b01 -> c11
100 - invalid
101 - b10 -> c01
110 - b11 -> c10
111 - invalid
Of course we finish each step with assigning best sums back to b
s.
When we processed all the coins we must drop the solutions that are incompatible with the initial assumption. Bits i-2
, i-1
and 0
must produce valid sequences.
This is example run for 123456
sequence.
A. assume first bit 0
1 a[1] = 2: b01 = 2, b10 = 999, b11 = 999
2 a[2] = 3: b01 = 1002, b10 = 2, b11 = 5
3 a[3] = 4: b01 = 6, b10 = 9, b11 = 1006
4 a[4] = 5: b01 = 13, b10 = 6, b11 = 11
5 a[5] = 6: b01 = 12, b10 = 13, b11 = 19
b10
is unacceptable, we choose better from b01
and b11
, which is 12.
B. assume first bit 1
1 a[1] = 2: b01 = 999, b10 = 1, b11 = 3
2 a[2] = 3: b01 = 4, b10 = 3, b11 = 1002
3 a[3] = 4: b01 = 7, b10 = 4, b11 = 8
4 a[4] = 5: b01 = 9, b10 = 12, b11 = 12
5 a[5] = 6: b01 = 18, b10 = 9, b11 = 15
Now b11
is invalid as it would produce 111
. So we choose best of b01
and b10
, which is 9. Step A gave 12, step B gave 9. 9 is better. This is the result.
I made the above calculations manually, so sorry if there is a mistake in them. However for the first coin unset I computed 2+4+6 and for first coin set the result was 1+3+5. Seems to be right.