Minimum Number of K Consecutive Bit Flips

Hard

Topics
ArrayBit ManipulationSliding WindowPrefix Sum

You are given a binary array nums and an integer target (the flip window length k). In one operation you choose a contiguous subarray of length exactly k and flip every bit in it. Return the minimum number of operations needed to make every element 1, or -1 if it is impossible.

Example 1

Input:  nums = [0,1,0], target = 1
Output: 2

Example 2

Input:  nums = [1,1,0], target = 2
Output: -1

Example 3

Input:  nums = [0,0,0,1,0,1,1,0], target = 3
Output: 3

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= target <= nums.length
  • nums[i] is 0 or 1.
Run ⌘' · Submit ⌘⏎