Maximum Number of Operations to Move Ones to the End - Problem

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 = "001010".

Return the maximum number of operations that you can perform.

Input & Output

Example 1 — Basic Case
$ Input: s = "1001101"
Output: 5
💡 Note: From right to left: '1' sees 0 zeros, '0' increments zeros to 1, '1' sees 1 zero (ops=1), '1' sees 1 zero (ops=2), '0' increments zeros to 2, '0' increments zeros to 3, '1' sees 3 zeros (ops=5). Total: 5 operations.
Example 2 — All Ones
$ Input: s = "1111"
Output: 0
💡 Note: No zeros to move through, so no operations possible
Example 3 — Alternating Pattern
$ Input: s = "10101"
Output: 3
💡 Note: From right: '1' sees 0 zeros, '0' increments zeros to 1, '1' sees 1 zero (ops=1), '0' increments zeros to 2, '1' sees 2 zeros (ops=3)

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of '0' and '1'

Visualization

Tap to expand
Maximum Operations to Move Ones to End INPUT Binary String s: 1 0 0 1 0 2 1 3 1 4 0 5 1 6 = '1' (can move) = '0' (target) Count of '1's: 4 Count of '0's: 3 Input Values: s = "1001101" Length = 7 ALGORITHM STEPS 1 Initialize Counters ones = 0, ops = 0 2 Scan Left to Right For each char in string 3 If char == '1' Increment ones count 4 If char == '0' ops += ones (all 1s move) Execution Trace: i=0: '1' --> ones=1, ops=0 i=1: '0' --> ones=1, ops=1 i=2: '0' --> ones=1, ops=2 i=3: '1' --> ones=2, ops=2 i=4: '1' --> ones=3, ops=2 i=5: '0' --> ones=3, ops=5 i=6: '1' --> ones=4, ops=5 FINAL RESULT After all operations: 0 0 0 1 1 1 1 "0001111" Operations Breakdown: Position 1: 1 op (first '1') Position 2: 1 op (first '1') Position 5: 3 ops (three '1's) Total: 1+1+3 = 5 ops max OUTPUT 4 [OK] Maximum operations Key Insight: When we encounter a '0', ALL '1's seen so far need to jump over it. Each '1' jumping over a '0' counts as one operation. So we track count of '1's and add it to operations at each '0'. TutorialsPoint - Maximum Number of Operations to Move Ones to the End | Greedy Counting Approach
Asked in
Google 12 Amazon 8 Microsoft 5
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen