[LeetCode] Minimum Swaps to Group All 1's Together

1151. Minimum Swaps to Group All 1’s Together

Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int minSwaps(vector<int>& data) {
int sum = 0;
for(int i = 0; i < data.size(); i++) {
sum += data[i];
data[i] += (i ? data[i - 1] : 0);
}
if(!sum) return 0;
int res = sum - data[sum - 1];
for(int i = sum; i < data.size(); i++) {
res = min(res, sum - data[i] + data[i - sum]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/23/PS/LeetCode/minimum-swaps-to-group-all-1s-together/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.