Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1626b51

Browse files
Create 3666-minimum-operations-to-equalize-binary-string.js
1 parent e8479f9 commit 1626b51

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {string} s
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
var minOperations = function(s, k) {
7+
const N = s.length;
8+
const Z = [...s].filter(c => c === '0').length;
9+
const inf = Infinity;
10+
11+
if (N === k) {
12+
if (Z === 0) return 0;
13+
else if (Z === N) return 1;
14+
else return -1;
15+
}
16+
17+
let res = inf;
18+
if (Z % 2 === 0) {
19+
let M = Math.max(ceil(Z, k), ceil(Z, N - k));
20+
M += M & 1;
21+
res = Math.min(res, M);
22+
}
23+
if (Z % 2 === k % 2) {
24+
let M = Math.max(ceil(Z, k), ceil(N - Z, N - k));
25+
M += (M & 1) === 0 ? 1 : 0;
26+
res = Math.min(res, M);
27+
}
28+
29+
return res < inf ? res : -1;
30+
};
31+
function ceil(x, y) {
32+
return Math.floor((x + y - 1) / y);
33+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /