From 4d58693febf5b475cab5e78ded15fa37d6542a92 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Fri, 2 Aug 2024 16:45:45 +0530 Subject: [PATCH] Create 2134. Minimum Swaps to Group All 1's Together II --- ...Minimum Swaps to Group All 1's Together II | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 2134. Minimum Swaps to Group All 1's Together II 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; + } +};