LeetCode Challenge Day 59 β 3228. Maximum Number of Operations to Move Ones to the End
Nitin Ahirwal / November 13, 2025
Hey folks π
This is Day 59 of my LeetCode streak π
Todayβs problem is 3228. Maximum Number of Operations to Move Ones to the End β a medium-level greedy + counting problem based on understanding patterns inside a binary string.
Instead of simulating each operation, the trick is to observe how zero-block boundaries control the number of possible moves.
π Problem Statement
You are given a binary string s.
You may perform the following operation any number of times:
- Choose an index
isuch thats[i] == '1'ands[i + 1] == '0' - Move that
'1'to the right until it reaches:- the end of the string, or
- another
'1'
Return the maximum number of operations possible.
Example 1:
Input: "1001101"
Output: 4
Example 2:
Input: "00111"
Output: 0
π‘ Intuition
Whenever a '1' is followed by a '0', it can produce one operation.
But instead of checking each pair, we notice:
π Only the last zero of each consecutive zero-block contributes to the final count.
Each such zero-block end allows all previously seen '1's to βjumpβ over it.
So we scan the string once and count operations based on block structure.
π Approach
- Traverse the string from left to right.
- Maintain
onesβ number of'1's seen so far. - For each
'0':- Check if it is the end of a zero-block
(i.e., next char is'1'or we are at the last index). - If yes β add
onesto the answer.
- Check if it is the end of a zero-block
- Return the final count.
This avoids any simulation and leverages pure counting.
β±οΈ Complexity Analysis
-
Time Complexity:
( O(n) ) -
Space Complexity:
( O(1) )
π§βπ» Code (JavaScript)
/**
* @param {string} s
* @return {number}
*/
var maxOperations = function(s) {
let ans = 0;
let ones = 0;
const n = s.length;
for (let i = 0; i < n; ++i) {
if (s[i] === '1') {
ones += 1;
} else { // s[i] === '0'
// If this zero is the last in its zero-block
if (i === n - 1 || s[i + 1] === '1') {
ans += ones;
}
}
}
return ans;
};
π― Example Walkthrough
Input:
"1001101"
Zero-block ends at positions:
-
index 2 β adds 1
-
index 4 β adds 2
-
index 5 β adds 4
Total = 4 operations
π― Reflection
This problem highlights how recognizing patterns and block structures in strings can eliminate the need for simulation and drastically simplify logic.
See you tomorrow for Day 60 β the grind continues! πͺ
Happy Coding π¨βπ»β¨