From 59cf35cb3aaf1d77ae4e380546dec38ec013399d Mon Sep 17 00:00:00 2001 From: zhaocchen Date: Mon, 10 Jan 2022 12:41:07 +0800 Subject: [PATCH] feat: add typescript solution to lc problem: No.2134 No.2134.Minimum Swaps to Group All 1's Together II --- .../README.md | 14 +++++++++++++- .../README_EN.md | 14 +++++++++++++- .../Solution.ts | 13 +++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/Solution.ts diff --git a/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README.md b/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README.md index 4db249ef4c904..903c202bfc2c5 100644 --- a/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README.md +++ b/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README.md @@ -80,7 +80,19 @@ ```ts - +function minSwaps(nums: number[]): number { + const n = nums.length; + const m = nums.reduce((a, c) => a + c, 0); + let cnt = nums.reduce((a, c, i) => a + (i < m ? c : 0), 0); + let ans = cnt; + for (let i = m; i < m + n; i++) { + let prev = nums[i - m]; + let post = nums[i % n]; + cnt += (post - prev); + ans = Math.max(cnt, ans); + } + return m - ans; +}; ``` ### **...** diff --git a/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README_EN.md b/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README_EN.md index 1b69a77fff7b8..62995520c4e2b 100644 --- a/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README_EN.md +++ b/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README_EN.md @@ -72,7 +72,19 @@ Thus, the minimum number of swaps required is 0. ### **TypeScript** ```ts - +function minSwaps(nums: number[]): number { + const n = nums.length; + const m = nums.reduce((a, c) => a + c, 0); + let cnt = nums.reduce((a, c, i) => a + (i < m ? c : 0), 0); + let ans = cnt; + for (let i = m; i < m + n; i++) { + let prev = nums[i - m]; + let post = nums[i % n]; + cnt += (post - prev); + ans = Math.max(cnt, ans); + } + return m - ans; +}; ``` ### **...** diff --git a/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/Solution.ts b/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/Solution.ts new file mode 100644 index 0000000000000..9f3d861dc8391 --- /dev/null +++ b/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/Solution.ts @@ -0,0 +1,13 @@ +function minSwaps(nums: number[]): number { + const n = nums.length; + const m = nums.reduce((a, c) => a + c, 0); + let cnt = nums.reduce((a, c, i) => a + (i < m ? c : 0), 0); + let ans = cnt; + for (let i = m; i < m + n; i++) { + let prev = nums[i - m]; + let post = nums[i % n]; + cnt += (post - prev); + ans = Math.max(cnt, ans); + } + return m - ans; +}; \ No newline at end of file