LeetCode-in-Java

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

Medium

You are given a binary string s.

You can perform the following operation on the string any number of times:

Return the maximum number of operations that you can perform.

Example 1:

Input: s = “1001101”

Output: 4

Explanation:

We can perform the following operations:

Example 2:

Input: s = “00111”

Output: 0

Constraints:

Solution

public class Solution {
    public int maxOperations(String s) {
        char[] arr = s.toCharArray();
        int result = 0;
        int ones = 0;
        int n = arr.length;
        for (int i = 0; i < n; ++i) {
            ones += arr[i] - '0';
            if (i > 0 && arr[i] < arr[i - 1]) {
                result += ones;
            }
        }
        return result;
    }
}