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:
parent
649c2f92fa
commit
79db7a329c
1 changed files with 27 additions and 0 deletions
27
java/minimum-swaps-to-group-all-1s-together-ii.java
Normal file
27
java/minimum-swaps-to-group-all-1s-together-ii.java
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue