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 = "0** _001_** 10".
Return the maximum number of operations that you can perform.
Input: s ="1001101"Output: 4Explanation:
We can perform the following operations:* Choose index `i = 0`. The resulting string is`s = "_**001**_ 1101"`.* Choose index `i = 4`. The resulting string is`s = "0011 _**01**_ 1"`.* Choose index `i = 3`. The resulting string is`s = "001** _01_** 11"`.* Choose index `i = 2`. The resulting string is`s = "00** _01_** 111"`.
Each ‘1’ can be moved to the end by swapping with ‘0’s to its right. The number of operations is the sum of the number of ‘0’s to the right of each ‘1’.
classSolution {
publiclongmaximumOperations(String s) {
long ans = 0, zeros = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) =='0') zeros++;
else ans += zeros;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funmaximumOperations(s: String): Long {
var ans = 0Lvar zeros = 0Lfor (i in s.length - 1 downTo 0) {
if (s[i] =='0') zeros++else ans += zeros
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defmaximumOperations(self, s: str) -> int:
ans = zeros =0for c in reversed(s):
if c =='0':
zeros +=1else:
ans += zeros
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnmaximum_operations(s: String) -> i64 {
letmut ans =0;
letmut zeros =0;
for c in s.chars().rev() {
if c =='0' {
zeros +=1;
} else {
ans += zeros;
}
}
ans
}
}