Skip to content

Commit 87940c3

Browse files
authored
feat: add typescript solution to lc problem: No.2134 (doocs#664)
No.2134.Minimum Swaps to Group All 1's Together II
1 parent e49a9f8 commit 87940c3

File tree

3 files changed

+39
-2
lines changed

3 files changed

+39
-2
lines changed

solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README.md

+13-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,19 @@
8080
<!-- 这里可写当前语言的特殊实现逻辑 -->
8181

8282
```ts
83-
83+
function minSwaps(nums: number[]): number {
84+
const n = nums.length;
85+
const m = nums.reduce((a, c) => a + c, 0);
86+
let cnt = nums.reduce((a, c, i) => a + (i < m ? c : 0), 0);
87+
let ans = cnt;
88+
for (let i = m; i < m + n; i++) {
89+
let prev = nums[i - m];
90+
let post = nums[i % n];
91+
cnt += (post - prev);
92+
ans = Math.max(cnt, ans);
93+
}
94+
return m - ans;
95+
};
8496
```
8597

8698
### **...**

solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README_EN.md

+13-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,19 @@ Thus, the minimum number of swaps required is 0.
7272
### **TypeScript**
7373

7474
```ts
75-
75+
function minSwaps(nums: number[]): number {
76+
const n = nums.length;
77+
const m = nums.reduce((a, c) => a + c, 0);
78+
let cnt = nums.reduce((a, c, i) => a + (i < m ? c : 0), 0);
79+
let ans = cnt;
80+
for (let i = m; i < m + n; i++) {
81+
let prev = nums[i - m];
82+
let post = nums[i % n];
83+
cnt += (post - prev);
84+
ans = Math.max(cnt, ans);
85+
}
86+
return m - ans;
87+
};
7688
```
7789

7890
### **...**
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
function minSwaps(nums: number[]): number {
2+
const n = nums.length;
3+
const m = nums.reduce((a, c) => a + c, 0);
4+
let cnt = nums.reduce((a, c, i) => a + (i < m ? c : 0), 0);
5+
let ans = cnt;
6+
for (let i = m; i < m + n; i++) {
7+
let prev = nums[i - m];
8+
let post = nums[i % n];
9+
cnt += (post - prev);
10+
ans = Math.max(cnt, ans);
11+
}
12+
return m - ans;
13+
};

0 commit comments

Comments
 (0)