LeetCode/java/minimum-swaps-to-group-all-1s-together-ii.java
2024-08-02 13:18:13 +02:00

27 lines
564 B
Java

class Solution {
private int countOnes(int[] nums, int upperBound) {
var count = 0;
for (int i = 0; i < upperBound; ++i) {
if (nums[i] == 1) {
++count;
}
}
return count;
}
public int minSwaps(int[] nums) {
var ones = countOnes(nums, nums.length);
var inWindow = countOnes(nums, ones);
var minSwaps = nums.length;
for (int i = 0; i < nums.length; ++i) {
inWindow += nums[(i + ones) % nums.length] - nums[i];
minSwaps = Math.min(minSwaps, ones - inWindow);
}
return minSwaps;
}
}