java: add «2134. Minimum Swaps to Group All 1's Together II»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-02 13:18:13 +02:00
parent 649c2f92fa
commit 79db7a329c
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,27 @@
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;
}
}