Skip to content

Commit

Permalink
2024-08-03 Minimum Swaps to Group All 1's Together 2
Browse files Browse the repository at this point in the history
  • Loading branch information
InSange committed Aug 3, 2024
1 parent e63fc7a commit d06f6f0
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions InSange/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <vector>

using namespace std;

class Solution {
public:
int minSwaps(vector<int>& nums) {
int zeroCnt = minSwapsHelper(nums, 0);
int oneCnt = minSwapsHelper(nums, 1);

return min(zeroCnt, oneCnt);
}

int minSwapsHelper(vector<int>& 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;
}
};

0 comments on commit d06f6f0

Please sign in to comment.