1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 09:59:41 +01:00
LeetCode/java/minimum-swaps-to-group-all-1s-together-ii.java

28 lines
564 B
Java
Raw Normal View History

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;
}
}