#1703

Minimum Adjacent Swaps for K Consecutive Ones

master · 1640 · lc hard +32 · verified · 42.3% accepted · 743 likes · top 23%

Description

You are given an integer array nums containing only 0s and 1s, and an integer k. In one move you may swap two adjacent elements. Return the minimum number of moves required so that nums contains k consecutive 1s.

Example 1:

Input: nums = [1,0,0,1,0,1], k = 2
Output: 1
Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.

Example 2:

Input: nums = [1,0,0,0,0,0,1,1], k = 3
Output: 5
Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].

Example 3:

Input: nums = [1,1,0,1], k = 2
Output: 0
Explanation: nums already has 2 consecutive 1's.

Code

1
2
3