跳至主要内容

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

Hint

class Solution {
public:
int maxOperations(string s)
{
// Initialize the result variable to store the maximum number of operations.
// Initialize the counter to count consecutive '1's.

// Iterate over each character in the string.
for ()
{
// If the current character is '1', increment the counter.
// If the current character is '0' and the previous character was '1',
// add the count of '1's to the result.
}
// Return the result which is the maximum number of operations.
}
};
class Solution {
public:
int maxOperations(string s)
{
int res = 0, cnt = 0;
for (int i = 0; i < s.size(); ++i)
{
if (s[i] == '1') ++cnt;
else if (i > 0 && s[i - 1] == '1') res += cnt;
}
return res;
}
};
  • T: O(n)O(n)
  • S: O(1)O(1)