I want to find the minimum number of flips required to get an alternating of [0, 1, 0, 1] for example given [1, 1, 0, 1]. so in this case, it is one flip.
def solution(A):
count = 0
myDict = {}
myDict[1] = True
myDict[0] = False
next = None
# first element value
val = myDict[A[0]]
if val == True:
next = False
else:
next = True
for element in A[1:]:
if next != myDict[element]:
count += 1
# do something to update element
myDict[element] = next
if myDict[element] == True:
next = False
else:
next = True
return count
My solution does not work for the input [1, 1, 0, 1, 1]. Because it gives back 3 when the answer it should give back is 2(change the first index and last index elements to 0). How can i solve this?
You could just count the differences for each kind of pattern and take the min
def minFlip(a):
return min(
sum(n == i % 2 for i, n in enumerate(a)),
sum(n == (i + 1) % 2 for i, n in enumerate(a))
)
minFlip([1, 1, 0, 1, 1])
#2
minFlip([0, 1, 0, 1, 0])
#0
minFlip([1, 1, 1, 1, 1])
#2
minFlip([0, 0, 0, 0, 0])
#2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With