diff --git a/leetcode/problems/java/minimum-swaps-to-group-all-1s-together-ii.java b/leetcode/problems/java/minimum-swaps-to-group-all-1s-together-ii.java new file mode 100644 index 0000000..33d136f --- /dev/null +++ b/leetcode/problems/java/minimum-swaps-to-group-all-1s-together-ii.java @@ -0,0 +1,17 @@ +import java.util.Arrays; + +class Solution { + public int minSwaps(int[] nums) { + int k = Arrays.stream(nums).sum(); + int n = nums.length; + int count = 0; + for (int i = 0; i < k; ++i) + count += nums[i]; + int max = count; + for (int i = k; i < n + k; ++i) { + count += nums[i % n] - nums[(i - k + n) % n]; + max = Math.max(max, count); + } + return k - max; + } +} \ No newline at end of file