Skip to content

Commit ade6f75

Browse files
authored
Create 1151-minimum-swaps-to-group-all-1s-together.js
1 parent 987d4d0 commit ade6f75

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {number[]} data
3+
* @return {number}
4+
*/
5+
const minSwaps = function(data) {
6+
let num = 0, n = data.length
7+
const arr = Array(n).fill(0)
8+
for(let i = 0; i < n; i++) {
9+
const e = data[i]
10+
if(e === 1) {
11+
num++
12+
}
13+
arr[i] = num
14+
}
15+
if(num === 0) return 0
16+
let res = num - arr[num - 1]
17+
for(let i = num; i < n; i++) {
18+
res = Math.min(res, num - (arr[i] - arr[i - num]))
19+
}
20+
return res
21+
};

0 commit comments

Comments
 (0)