LeetCode: Maximum Number of Operations to Move Ones to the End

Return the maximum number of operations to move ones to the end of a binary string.

Posted on LeetCode Python

Solution

We don’t actualy need to perform the swap operations. Instead we can can count the number of groups of zeros as we iterate backwards through the binary string.

Runtime

63 ms | Beats 56.68%

class Solution:
def maxOperations(self, s: str) -> int:
zero_groups = 0
total = 0
n = len(s)
for i in range(n - 1, -1, -1):
if s[i] == "0":
if i == n - 1 or s[i + 1] == "1":
zero_groups += 1
else:
total += zero_groups
return total