Advertisement
3228. Maximum Number of Operations to Move Ones to the End
UnknownView on LeetCode
Time: O(n)
Space: O(1)
Approach
For each 1 count zeros to its right; sum = total operations.
3228.cs
C#
// Approach: For each 1 count zeros to its right; sum = total operations.
// Time: O(n) Space: O(1)
public class Solution
{
public int MaxOperations(string s)
{
int ans = 0;
int ones = 0;
for (int i = 0; i < s.Length; ++i)
{
if (s[i] == '1')
++ones;
else if (i == s.Length - 1 || s[i + 1] == '1')
ans += ones;
}
return ans;
}
}Advertisement
Was this solution helpful?