Skip to content

Commit 87d20e6

Browse files
authored
Update 1703-maximum-binary-string-after-change.js
1 parent 70c3d15 commit 87d20e6

File tree

1 file changed

+28
-28
lines changed

1 file changed

+28
-28
lines changed
+28-28
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,30 @@
11
/**
2-
* @param {string} binary
3-
* @return {string}
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
45
*/
5-
const maximumBinaryString = function(binary) {
6-
let n = binary.length;
7-
const {max} = Math
8-
let nums = [];
9-
for (let i = 0; i < n; ++i) {
10-
nums.push(+binary[i]);
11-
}
12-
for (let i = 0, j = 0; i < n - 1; ++i) {
13-
if (nums[i] == 1) continue;
14-
if (nums[i + 1] == 0) {
15-
nums[i] = 1;
16-
continue;
17-
}
18-
j = max(j, i + 1);
19-
while (j < n && nums[j]) ++j;
20-
if (j === n) break;
21-
nums[j++] = 1;
22-
nums[i + 1] = 0;
23-
nums[i] = 1;
24-
}
25-
let res = "";
26-
for (let i = 0; i < n; ++i) {
27-
res += (nums[i] + '');
28-
}
29-
return res;
30-
};
6+
const minMoves = function (nums, k) {
7+
if (k === 1) return 0
8+
let n = 0
9+
const pos = []
10+
for (let i = 0; i < nums.length; ++i) {
11+
if (nums[i]) pos.push(i - n++)
12+
}
13+
const sums = []
14+
sums[0] = pos[0]
15+
for (let i = 1; i < n; ++i) sums[i] = pos[i] + sums[i - 1]
16+
let res = Number.MAX_VALUE
17+
let l = (k / 2) >> 0,
18+
r = k - l - 1
19+
for (let i = 0; i + k <= n; ++i) {
20+
const m = i + ((k / 2) >>> 0)
21+
const cur =
22+
pos[m] * l -
23+
(sums[m - 1] - sums[i] + pos[i]) -
24+
pos[m] * r +
25+
sums[i + k - 1] -
26+
sums[m]
27+
res = Math.min(cur, res)
28+
}
29+
return res
30+
}

0 commit comments

Comments
 (0)