Minimum Swaps to Group All 1's Together II

medium array sliding window

Problem

A binary circular array nums is given. Return the minimum number of swaps needed to gather all 1's together at any contiguous position on the circle.

Inputnums = [0,1,0,1,1,0,0]
Output1
Three 1's; the best window of size 3 holds 2 of them, so 1 swap suffices.

def min_swaps(nums):
    n = len(nums)
    w = sum(nums)
    if w <= 1:
        return 0
    cur = sum(nums[:w])
    best = cur
    for i in range(1, n):
        cur += nums[(i + w - 1) % n] - nums[i - 1]
        best = max(best, cur)
    return w - best
function minSwaps(nums) {
  const n = nums.length;
  let w = 0;
  for (const x of nums) w += x;
  if (w <= 1) return 0;
  let cur = 0;
  for (let i = 0; i < w; i++) cur += nums[i];
  let best = cur;
  for (let i = 1; i < n; i++) {
    cur += nums[(i + w - 1) % n] - nums[i - 1];
    best = Math.max(best, cur);
  }
  return w - best;
}
class Solution {
    public int minSwaps(int[] nums) {
        int n = nums.length, w = 0;
        for (int x : nums) w += x;
        if (w <= 1) return 0;
        int cur = 0;
        for (int i = 0; i < w; i++) cur += nums[i];
        int best = cur;
        for (int i = 1; i < n; i++) {
            cur += nums[(i + w - 1) % n] - nums[i - 1];
            best = Math.max(best, cur);
        }
        return w - best;
    }
}
int minSwaps(vector<int>& nums) {
    int n = nums.size(), w = 0;
    for (int x : nums) w += x;
    if (w <= 1) return 0;
    int cur = 0;
    for (int i = 0; i < w; i++) cur += nums[i];
    int best = cur;
    for (int i = 1; i < n; i++) {
        cur += nums[(i + w - 1) % n] - nums[i - 1];
        best = max(best, cur);
    }
    return w - best;
}
Time: O(n) Space: O(1)