[LeetCode] Maximum Number of Operations to Move Ones to the End

3228. Maximum Number of Operations to Move Ones to the End

You are given a binary string s.

You can perform the following operation on the string any number of times:

  • Choose any index i from the string where i + 1 < s.length such that s[i] == '1' and s[i + 1] == '0'.
  • Move the character s[i] to the right until it reaches the end of the string or another '1'. For example, for s = "010010", if we choose i = 1, the resulting string will be s = "0**001**10".

Return the maximum number of operations that you can perform.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

class Solution {
public:
int maxOperations(string& s) {
int res = 0, o = 0, fl = false;
s.push_back('1');
for(auto& ch : s) {
if(ch == '1') {
if(fl) res += o;
o++;
fl = false;
} else fl = true;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/07/21/PS/LeetCode/maximum-number-of-operations-to-move-ones-to-the-end/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.