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.
1#include <stdio.h>
2
3int minSwaps(int* nums, int numsSize) {
4 int totalOnes = 0;
5 for
This C solution uses a sliding window method adapted for a circular array by processing a concatenated array. We calculate the number of swaps needed as the difference between the total number of 1's and the maximum number of 1's found within any sliding window of size equal to the total number of 1's. We iterate twice the array length, using modulus to simulate the circular part and effectively sliding over the concatenated version.