Minimum Moves to Pick K Ones

You are given a binary array nums of length n, a positive integer k, and a non-negative integer maxChanges.

Alice plays a game where the goal is to pick up k ones from nums using the minimum number of moves. When the game starts, Alice chooses any index aliceIndex in the range [0, n - 1] and stands there. If nums[aliceIndex] == 1, Alice picks up the one and nums[aliceIndex] becomes 0; this does not count as a move.

After this, Alice can make any number of moves, including zero, where in each move Alice must perform exactly one of the following actions:

  • Select any index j != aliceIndex such that nums[j] == 0 and set nums[j] = 1. This action can be performed at most maxChanges times.
  • Select any two adjacent indices x and y where |x - y| == 1, nums[x] == 1, and nums[y] == 0, then swap their values by setting nums[y] = 1 and nums[x] = 0. If y == aliceIndex, Alice picks up the one after this move and nums[y] becomes 0.

Return the minimum number of moves required by Alice to pick exactly k ones.

Example 1
Inputnums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1
Output3
By standing at index 1, Alice can pick the initial one, create a one at index 2 and move it in, then move the one from index 0 in, for a total of 3 moves.
Example 2
Inputnums = [0,0,0,0], k = 2, maxChanges = 3
Output4
Alice can stand at index 0, create a one at index 1 and move it into index 0 twice, requiring 4 total moves.

Constraints

  • 2 <= n <= 10^5
  • 0 <= nums[i] <= 1
  • 1 <= k <= 10^5
  • 0 <= maxChanges <= 10^5
  • maxChanges + sum(nums) >= k

Asked at 1 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