Maximum Number of Operations to Move Ones to the End Problem
#3228
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3228.
You are given a binary string s.
You can perform the following operation on the string any number of times:
- Choose any index
ifrom the string wherei + 1 < s.lengthsuch thats[i] == '1'ands[i + 1] == '0'. - Move the character
s[i]to the right until it reaches the end of the string or another'1'. For example, fors = "010010", if we choosei = 1, the resulting string will bes = "0**001**10".
Return the maximum number of operations that you can perform.
Example 1:
Input: s = "1001101"
Output: 4
Explanation:
We can perform the following operations:
- Choose index i = 0. The resulting string is s = "0011101".
- Choose index i = 4. The resulting string is s = "0011011".
- Choose index i = 3. The resulting string is s = "0010111".
- Choose index i = 2. The resulting string is s = "0001111".
Example 2:
Input: s = "00111"
Output: 0
Constraints:
1 <= s.length <= 10^5s[i]is either'0'or'1'.
Solution
Approach: Greedy
Keep cnt, the number of 1s seen so far, and ans. Scan the string: for a 1, increase cnt. For a 0 that directly follows a 1, all cnt ones before it can be moved past this block of zeros, so add cnt to ans. Consecutive zeros count once, because the ones jump over the whole block in one operation each.
Complexity: time O(n), space O(1).
class Solution:
def maxOperations(self, s: str) -> int:
ans = cnt = 0
for i, c in enumerate(s):
if c == "1":
cnt += 1
elif i and s[i - 1] == "1":
ans += cnt
return ans