---
# System prepended metadata

title: 2134. Minimum Swaps to Group All 1's Together II
tags: [Leetcode, Sliding Window, Medium]

---

# 2134. Minimum Swaps to Group All 1's Together II
###### tags: `Leetcode` `Medium` `Sliding Window`
Link: https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/description/
## 思路
当遇到circular array的问题时，可以append the array to itself 这样就可以不管circular array的部分
固定长度的sliding window 长度为nums含有的1的个数```cntOnes```
找到sliding window里最多有几个1```maxOnesInWindow```
```cntOnes-maxOnesInWindow```就是答案
## Code
```java=
class Solution {
    public int minSwaps(int[] nums) {
        int cntOnes = 0;
        for(int num:nums) if(num==1) cntOnes++;
        int n = nums.length;
        int[] nums2 = new int[n*2];
        for(int i=0; i<2*n; i++){
            nums2[i] = nums[i%n];
        }
        int currCntOnes = 0;
        int maxOnesInWindow = 0;
        for(int i=0; i<2*n; i++){
            if(i>=cntOnes && nums2[i-cntOnes]==1) currCntOnes--;
            if(nums2[i]==1) currCntOnes++;
            maxOnesInWindow = Math.max(maxOnesInWindow, currCntOnes);
        }
        return cntOnes-maxOnesInWindow;
    }
}
```
```python=
class Solution:
    def minSwaps(self, nums: List[int]) -> int:
        ones = nums.count(1)
        nums = nums+nums
        currOnes = maxCntOnes = 0
        for i in range(len(nums)):
            if i>=ones and nums[i-ones]==1: currOnes -= 1
            if nums[i]==1: currOnes += 1
            maxCntOnes = max(maxCntOnes, currOnes)
        return ones-maxCntOnes
```