Minimum Adjacent Swaps for K Consecutive Ones

You are given an integer array nums and an integer k. nums consists only of 0's and 1's. In one move, you can choose two adjacent indices and swap their values.

Return the minimum number of moves required so that nums has k consecutive 1's.

Example 1
Inputnums = [1,0,0,1,0,1], k = 2
Output1
In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.
Example 2
Inputnums = [1,0,0,0,0,0,1,1], k = 3
Output5
In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is 0 or 1.
  • 1 <= k <= sum(nums)

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate