On any array other than the ones with all 0
s only two operations are possible. Either flip the nth element or flip the element right before the last 1
in the array.
We don't need to consider the edge case of only the first element being 1
because we can add any number of zeros to the beginning of the array and it doesn't change the result, i.e. [1, 0, 0, 0]
and [0, 1, 0, 0, 0]
need the same amount of minimum operations to become all 0
s.
This means that on every sequence of 0
and 1
s one of the operations will go one step closer to 0
s and the other operation goes one step further.
The result of these observations is that we actually have a numeric system much similar to binary and each operation can be seen as incrementing or decrementing a number by 1 and that means for every sequence of 0
s and 1
s there is an equivalent binary number and decimal number that is the number of steps between this number and 0.
I have found the relation between this system and binary which is like this:
If we iterate over the array from beginning to end and flip every element that comes after a 1
we get the equivalent binary. This operation needs to be done in place, meaning we mutate the array itself as we iterate and the result of each iteration affects the next iteration. I don't have a proof on why this is correct, maybe someone can provide a proof.
With all that said the algorithm itself is simple. This is in python:
a = [1, 0, 0, 0]
# convert to equivalent binary
for i in range(1, len(a)):
a[i] = int(not a[i]) if a[i-1] == 1 else a[i]
# convert to decimal
bin_str = ''.join(map(str, a))
print(int(bin_str, 2))
n
. I agree that OP should clarify the problem statement. – user3386109