DDSA Solutions

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

Time: O(n)
Space: O(1)

Problem Overview

Maximum Number of Operations to Move Ones to the End (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Greedy pattern in coding interviews. For each 1 count zeros to its right; sum = total operations.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

For each 1 count zeros to its right; sum = total operations.

Related patterns: Array, Greedy, Stack

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;
    }
}
Was this solution helpful?

Related Problems