LeetCode 1151. Minimum Swaps to Group All 1's Together (Medium)

Description:

Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.

Example 1:
Input: [1,0,1,0,1]
Output: 1
Explanation: 
There are 3 ways to group all 1's together:
[1,1,1,0,0] using 1 swap.
[0,1,1,1,0] using 2 swaps.
[0,0,1,1,1] using 1 swap.
The minimum is 1.
Example 2:
Input: [0,0,0,1,0]
Output: 0
Explanation: 
Since there is only one 1 in the array, no swaps needed.
Example 3:
Input: [1,0,1,0,1,0,0,1,1,0,1]
Output: 3
Explanation: 
One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
Note:
  1. 1 <= data.length <= 10^5
  2. 0 <= data[i] <= 1

Analysis:

In this problem, we will apply Sliding Window strategy.

  1. Find the number of ones in the given array which will also be the length of the fixed-size window. Here we use oneCount  to denote this number.
  2. Slide the window constructed in the step 1 1 1 to find the position where the window contains the most 1 1 1s. Here we use maxWinOneCount  to represent the maximum number of 1s in the window.
  3. The solution to the problem is just oneCount - maxWinOneCount.

The above scheme is provided by Karamurat.

The window slides like the following graph shows:
在这里插入图片描述


Code:
class Solution {
    public int minSwaps(int[] data) {
        // The variable represents the amount of 1 in the array,
        // it also represents the fixed window length.
        int oneCount = 0;
        for(int i = 0; i < data.length; i++) {
            oneCount += data[i];
        }
    
        int maxWinOneCount = 0;
        int winOneCount = 0;
        
        for(int i = 0; i < data.length; i++) {
            // Increase the value of the element entering the window.
            winOneCount += data[i];
            // Decrease the value of the element leaving the window.
            int left = i - oneCount;
            if(left >= 0) {
                winOneCount -= data[left];
            }
            // If the whole window is in the array, then compare the winOneCount with maxWinOneCount.
            if(left+1 >= 0) {
                maxWinOneCount = Math.max(maxWinOneCount, winOneCount);
            }
        }
        return oneCount - maxWinOneCount;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值