From d06f6f06e1f1044e15fe0c8dcec2a19f82fc6df0 Mon Sep 17 00:00:00 2001 From: InSange Date: Sat, 3 Aug 2024 21:24:15 +0900 Subject: [PATCH] 2024-08-03 Minimum Swaps to Group All 1's Together 2 --- InSange/README.md | 1 + ...mum Swaps to Group All 1's Together 2.cpp" | 42 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 "InSange/\354\212\254\353\235\274\354\235\264\353\224\251 \354\234\210\353\217\204\354\232\260/2134_Minimum Swaps to Group All 1's Together 2.cpp" diff --git a/InSange/README.md b/InSange/README.md index 4d05640..ec243be 100644 --- a/InSange/README.md +++ b/InSange/README.md @@ -24,6 +24,7 @@ | 20차시 | 2024.07.17 | 스택 | [Robot Collisions](https://leetcode.com/problems/robot-collisions/) | [#20](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/74)] | 21차시 | 2024.07.21 | 그리디 | [Find Valid Matrix Given Row and Column Sums](https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/) | [#21](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/75)] | 22차시 | 2024.07.31 | DP | [Filling Bookcase Shelves](https://leetcode.com/problems/filling-bookcase-shelves/) | [#22](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/81)] +| 23차시 | 2024.08.03 | 슬라이딩 윈도우 | [Minimum Swaps to Group All 1's Together 2](https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/) | [#23](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/82)] --- https://leetcode.com/problems/robot-collisions/ diff --git "a/InSange/\354\212\254\353\235\274\354\235\264\353\224\251 \354\234\210\353\217\204\354\232\260/2134_Minimum Swaps to Group All 1's Together 2.cpp" "b/InSange/\354\212\254\353\235\274\354\235\264\353\224\251 \354\234\210\353\217\204\354\232\260/2134_Minimum Swaps to Group All 1's Together 2.cpp" new file mode 100644 index 0000000..22f541d --- /dev/null +++ "b/InSange/\354\212\254\353\235\274\354\235\264\353\224\251 \354\234\210\353\217\204\354\232\260/2134_Minimum Swaps to Group All 1's Together 2.cpp" @@ -0,0 +1,42 @@ +#include + +using namespace std; + +class Solution { +public: + int minSwaps(vector& nums) { + int zeroCnt = minSwapsHelper(nums, 0); + int oneCnt = minSwapsHelper(nums, 1); + + return min(zeroCnt, oneCnt); + } + + int minSwapsHelper(vector& data, int val) { + int numSize = data.size(); + int totalCnt = 0; + + for (int num : data) + { + if (num == val) totalCnt++; + } + + if (totalCnt == 0 || totalCnt == numSize) return 0; + + int start = 0, end = 0; + int maxValCnt = 0, curValCnt = 0; + + while (end < totalCnt) { + if (data[end++] == val) curValCnt++; + } + maxValCnt = max(maxValCnt, curValCnt); + + while (end < numSize) + { + if (data[start++] == val) curValCnt--; + if (data[end++] == val) curValCnt++; + maxValCnt = max(maxValCnt, curValCnt); + } + + return totalCnt - maxValCnt; + } +}; \ No newline at end of file