[LeetCode] Separate Black and White Balls

2938. Separate Black and White Balls

There are n balls on a table, each ball has a color black or white.

You are given a 0-indexed binary string s of length n, where 1 and 0 represent black and white balls, respectively.

In each step, you can choose two adjacent balls and swap them.

Return the minimum number of steps to group all the black balls to the right and all the white balls to the left.

1
2
3
4
5
6
7
8
9
10
11
12
13

class Solution {
public:
long long minimumSteps(string s) {
long long res = 0, w = 0;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '0') res += w;
else w += 1;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/11/19/PS/LeetCode/separate-black-and-white-balls/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.