Problem : https://leetcode.com/problems/flip-string-to-monotone-increasing/
One valid monotone-increasing can either end by '0' or '1'.
For every s[i], consider the number of flip may need by appending it to the monotone-increasing ended by flipping s[i-1].
class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
N = len(s)
end_by_zero = 0 if s[0] == '0' else 1
end_by_one = 0 if s[1] == '1' else 0
for i in range(1, N):
if s[i] == '0':
# no need to flip to expand valid monotone increasing end by 0
# end_by_zero = end_by_zero
# flip 0 to 1 to expand valid monotone increasing end by 1
end_by_one = end_by_one + 1
elif s[i] == '1':
# no need to flip to expand valid monotone increasing end by 1
end_by_one = min(end_by_zero, end_by_one)
# flip 1 to 0 to expand valid monotone increasing end by 1
end_by_zero = end_by_zero + 1
return min(end_by_zero, end_by_one)
No comments:
Post a Comment