Skip to content

Commit 7e65333

Browse files
committed
https://leetcode.cn/problems/minimum-adjacent-swaps-for-k-consecutive-ones
1 parent 86a4871 commit 7e65333

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ Step 2. Add the dependency
4545

4646
<summary>展开查看</summary>
4747

48+
https://leetcode.cn/problems/minimum-adjacent-swaps-for-k-consecutive-ones
49+
4850
https://leetcode.cn/problems/form-array-by-concatenating-subarrays-of-another-array/
4951

5052
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
function minMoves(nums: number[], k: number): number {
2+
const g: number[] = [];
3+
const preSum: number[] = [];
4+
preSum.push(0);
5+
for (let i = 0; i < nums.length; i++) {
6+
if (nums[i] === 1) {
7+
g.push(i - g.length);
8+
preSum.push(preSum[preSum.length - 1] + g[g.length - 1]);
9+
}
10+
}
11+
const m = g.length;
12+
let res = Number.MAX_VALUE;
13+
for (let i = 0; i <= m - k; i++) {
14+
const mid = i + Math.floor(k / 2);
15+
const r = g[mid];
16+
res = Math.min(
17+
res,
18+
(1 - (k % 2)) * r +
19+
(preSum[i + k] - preSum[mid + 1]) -
20+
(preSum[mid] - preSum[i]),
21+
);
22+
}
23+
return res;
24+
}
25+
export default minMoves;

0 commit comments

Comments
 (0)