Sponsored
Sponsored
The goal is to find the minimum number of swaps needed to group all 1's together. First, count the total number of 1's, which determines the window size you are interested in. Use the sliding window technique to find the window with the maximum number of 1's. This will ensure that the remaining positions in this window must be filled with 1's by swapping.
Since the array is circular, concatenate the array with itself to simulate the wrap-around. Slide a window of the calculated size and keep track of the maximum number of 1's within this window. To minimize swaps, the window should contain the maximum possible 1's.
Time Complexity: O(n), where n is the size of the array, due to the sliding window.
Space Complexity: O(1), because the space used does not scale with input size.
1using System;
2
3class Solution {
4 public int MinSwaps(int[] nums) {
5 int totalOnes = 0;
6 foreach (int num in nums) if (num == 1) totalOnes++;
7
8 int maxOnes = 0, currentOnes = 0, n = nums.Length;
9 for (int i = 0; i < 2 * n; i++) {
10 if (i < totalOnes) currentOnes += nums[i % n];
11 else currentOnes += nums[i % n] - nums[(i - totalOnes) % n];
12
13 if (i >= totalOnes - 1) maxOnes = Math.Max(maxOnes, currentOnes);
}
return totalOnes - maxOnes;
}
public static void Main(string[] args) {
Solution sol = new Solution();
Console.WriteLine(sol.MinSwaps(new int[] {0, 1, 0, 1, 1, 0, 0}));
}
}
The C# version of the solution follows the same logic path, introducing intermediate variables and a loop that spans twice the array length for circular account. Sum increments and decrements simulate the sliding window within this doubly long array context.