Minimum Operations to Make Binary Array Elements Equal to One I

medium array greedy sliding window

Problem

You are given a binary array nums. In one operation you may choose any 3 consecutive elements and flip all of them (0 → 1, 1 → 0). Return the minimum number of operations needed to make every element equal to 1, or -1 if it is impossible.

Inputnums = [0,1,1,1,0,0]
Output3
Flip [0,1,2] → [1,0,0,1,0,0], flip [1,2,3] → [1,1,1,0,0,0], flip [3,4,5] → [1,1,1,1,1,1]. Three flips.

def minOperations(nums):
    n = len(nums)
    ops = 0
    # Scan left to right. The leftmost 0 can only be fixed
    # by flipping the window that starts at it.
    for i in range(n - 2):
        if nums[i] == 0:
            nums[i] ^= 1          # flip the 3 consecutive
            nums[i + 1] ^= 1      # elements i, i+1, i+2
            nums[i + 2] ^= 1
            ops += 1
    # The last two elements can no longer be touched.
    if nums[n - 1] == 0 or nums[n - 2] == 0:
        return -1
    return ops
function minOperations(nums) {
  const n = nums.length;
  let ops = 0;
  // Scan left to right. The leftmost 0 can only be fixed
  // by flipping the window that starts at it.
  for (let i = 0; i <= n - 3; i++) {
    if (nums[i] === 0) {
      nums[i] ^= 1;          // flip the 3 consecutive
      nums[i + 1] ^= 1;      // elements i, i+1, i+2
      nums[i + 2] ^= 1;
      ops++;
    }
  }
  // The last two elements can no longer be touched.
  if (nums[n - 1] === 0 || nums[n - 2] === 0) return -1;
  return ops;
}
int minOperations(int[] nums) {
    int n = nums.length;
    int ops = 0;
    // Scan left to right. The leftmost 0 can only be fixed
    // by flipping the window that starts at it.
    for (int i = 0; i <= n - 3; i++) {
        if (nums[i] == 0) {
            nums[i] ^= 1;          // flip the 3 consecutive
            nums[i + 1] ^= 1;      // elements i, i+1, i+2
            nums[i + 2] ^= 1;
            ops++;
        }
    }
    // The last two elements can no longer be touched.
    if (nums[n - 1] == 0 || nums[n - 2] == 0) return -1;
    return ops;
}
int minOperations(vector<int>& nums) {
    int n = nums.size();
    int ops = 0;
    // Scan left to right. The leftmost 0 can only be fixed
    // by flipping the window that starts at it.
    for (int i = 0; i <= n - 3; i++) {
        if (nums[i] == 0) {
            nums[i] ^= 1;          // flip the 3 consecutive
            nums[i + 1] ^= 1;      // elements i, i+1, i+2
            nums[i + 2] ^= 1;
            ops++;
        }
    }
    // The last two elements can no longer be touched.
    if (nums[n - 1] == 0 || nums[n - 2] == 0) return -1;
    return ops;
}
Time: O(n) Space: O(1)