Skip to main content
Back to problems
#3228
Medium Algorithms

Maximum number of operations to move ones to the end

String Greedy Counting
67.1% acceptance
Feb 25, 2026
530
38
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'. Return the maximum number of operations that you can perform.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_operations(s: String) -> i32 {
    // Each '1' contributes 1 op for each '0'-group to its right.
    // Scan right to left: track # of '0'-groups seen so far.
    let bytes = s.as_bytes();
    let n = bytes.len();
    let mut ops = 0i32;
    let mut groups_right = 0i32;
    let mut in_zero = false;
    for i in (0..n).rev() {
      if bytes[i] == b'0' {
        in_zero = true;
      } else {
        if in_zero {
          groups_right += 1;
          in_zero = false;
        }
        ops += groups_right;
      }
    }
    ops
  }
}