One canonical dynamic program would be to evaluate in O(1) time and space two states for each bit: the cost of keeping the bit the same or toggling it, while assigning it as rightmost of the relevant section (also incurring the relevant cost for the implied toggles due to the assignment).
Sorry, the above applies to the general problem - where "sorted" could be in either direction. (To choose a direction, pick the relevant one from the best variable assignments below.)
Python code:
def f(bits):
set_bits = sum(bits)
left_ones = 0
best = len(bits)
for i, bit in enumerate(bits):
right_ones = set_bits - left_ones - bit
left_zeros = i - left_ones
right_zeros = len(bits) - i - 1 - right_ones
# As rightmost 0
best = min(best, bit + left_ones + right_zeros)
# As rightmost 1
best = min(best, (bit ^ 1) + left_zeros + right_ones)
left_ones += bit
return best
Output:
bit_sets = [
[1,0,0,1,1], # 1
[1,0,0,1,0,1], # 2
[0,1,1,0,1,0], # 2
[1,1,1,1], # 0
[0,0,1,1], # 0
[0,1,0,0,0], # 1
[1,0,1,1,1] # 1
]
for bits in bit_sets:
print(f(bits), bits)