Tap here to switch tabs
Problem
Submissions

Problem: Minimum Moves to Pick K Ones

Try to solve the Minimum Moves to Pick K Ones problem.

Statement

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

Alice plays a game where her objective is to collect k ones. At the beginning of the game, Alice selects an index aliceIndex such that 0≤0 \leq aliceIndex <n< n. If nums[aliceIndex] is equal to 11, Alice immediately collects it, and nums[aliceIndex] becomes 00.

Afterward, in each move, Alice can perform one of the following actions:

  1. Select an index j such that 0≤j<n0 \leq j < n and nums[j] = 0, then set nums[j] = 1. This action can be performed at most maxChanges times in total throughout the game.

  2. Select two adjacent indices x and y such that ∣x−y∣=1|x - y| = 1, nums[x] = 1, and nums[y] = 0, then swap the values of nums[x] and nums[y]. If y is equal to aliceIndex, Alice immediately collects the one, and nums[y] becomes 00.

Return the minimum number of moves required for Alice to collect k ones.

Constraints:

  • 2≤2 \leq n ≤105\leq 10^5

  • 0≤0 \leq nums[i] ≤1\leq 1

  • 1≤1 \leq k ≤105\leq 10^5

  • 0≤0 \leq maxChanges ≤105\leq 10^5

  • maxChanges +extsum(+ ext{sum}(nums)≥) \geq k

⋮
Tap here to switch tabs
Problem
Submissions

Problem: Minimum Moves to Pick K Ones

Try to solve the Minimum Moves to Pick K Ones problem.

Statement

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

Alice plays a game where her objective is to collect k ones. At the beginning of the game, Alice selects an index aliceIndex such that 0≤0 \leq aliceIndex <n< n. If nums[aliceIndex] is equal to 11, Alice immediately collects it, and nums[aliceIndex] becomes 00.

Afterward, in each move, Alice can perform one of the following actions:

  1. Select an index j such that 0≤j<n0 \leq j < n and nums[j] = 0, then set nums[j] = 1. This action can be performed at most maxChanges times in total throughout the game.

  2. Select two adjacent indices x and y such that ∣x−y∣=1|x - y| = 1, nums[x] = 1, and nums[y] = 0, then swap the values of nums[x] and nums[y]. If y is equal to aliceIndex, Alice immediately collects the one, and nums[y] becomes 00.

Return the minimum number of moves required for Alice to collect k ones.

Constraints:

  • 2≤2 \leq n ≤105\leq 10^5

  • 0≤0 \leq nums[i] ≤1\leq 1

  • 1≤1 \leq k ≤105\leq 10^5

  • 0≤0 \leq maxChanges ≤105\leq 10^5

  • maxChanges +extsum(+ ext{sum}(nums)≥) \geq k