diff --git a/2134. Minimum Swaps to Group All 1's Together II b/2134. Minimum Swaps to Group All 1's Together II new file mode 100644 index 0000000..28613e3 --- /dev/null +++ b/2134. Minimum Swaps to Group All 1's Together II @@ -0,0 +1,40 @@ +class Solution { +public: + int minSwaps(vector& nums) { + int n = nums.size(); + int totalOnes = 0; + + for (int num : nums) { + if (num == 1) { + totalOnes++; + } + } + + if (totalOnes == 0 || totalOnes == n) { + return 0; + } + + int maxOnesInWindow = 0; + int currentOnesInWindow = 0; + + for (int i = 0; i < totalOnes; i++) { + if (nums[i] == 1) { + currentOnesInWindow++; + } + } + + maxOnesInWindow = currentOnesInWindow; + + for (int i = 1; i < n; i++) { + if (nums[i - 1] == 1) { + currentOnesInWindow--; + } + if (nums[(i + totalOnes - 1) % n] == 1) { + currentOnesInWindow++; + } + maxOnesInWindow = std::max(maxOnesInWindow, currentOnesInWindow); + } + + return totalOnes - maxOnesInWindow; + } +};