2134. Minimum Swaps to Group All 1's Together II #225
-
A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 2134. Minimum Swaps to Group All 1's Together II <?php
function minSwaps($nums) {
$n = count($nums);
$totalOnes = array_sum($nums);
// If there are no 1s, no swaps are needed
if ($totalOnes == 0) {
return 0;
}
// Extend the array by appending itself
$extendedNums = array_merge($nums, $nums);
// Initial count of 0s in the first window
$zeroCount = 0;
for ($i = 0; $i < $totalOnes; $i++) {
if ($extendedNums[$i] == 0) {
$zeroCount++;
}
}
$minSwaps = $zeroCount;
// Slide the window across the extended array
for ($i = $totalOnes; $i < count($extendedNums); $i++) {
if ($extendedNums[$i] == 0) {
$zeroCount++;
}
if ($extendedNums[$i - $totalOnes] == 0) {
$zeroCount--;
}
$minSwaps = min($minSwaps, $zeroCount);
}
return $minSwaps;
}
// Example usage
$nums1 = [0,1,0,1,1,0,0];
$nums2 = [0,1,1,1,0,0,1,1,0];
$nums3 = [1,1,0,0,1];
echo minSwaps($nums1) . "\n"; // Output: 1
echo minSwaps($nums2) . "\n"; // Output: 2
echo minSwaps($nums3) . "\n"; // Output: 0
?> Explanation:
This solution efficiently handles the circular array by transforming it into a linear problem and uses the sliding window technique to maintain a running count of |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
1
s: This will be the number of1
s we need to group together.Let's implement this solution in PHP: 2134. Minimum Swaps to Group All 1's Together II