Problem
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 for Alice to pick up k
ones from
nums
using the minimum number of moves. When the game starts, Alice picks up 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 thatnums[j] == 0
and setnums[j] = 1
. This action can be performed at mostmaxChanges
times. - Select any two adjacent indices
x
andy
(|x - y| == 1
) such thatnums[x] == 1
,nums[y] == 0
, then swap their values (setnums[y] = 1
andnums[x] = 0
). Ify == aliceIndex
, Alice picks up the one after this move andnums[y]
becomes0
.
Return theminimum number of moves required by Alice to pick
exactlyk
ones.
Examples
Example 1
|
|
Example 2
|
|
Constraints
2 <= n <= 10^5
0 <= nums[i] <= 1
1 <= k <= 10^5
0 <= maxChanges <= 10^5
maxChanges + sum(nums) >= k
Solution
Method 1 – Sliding Window + Greedy Simulation
Intuition
We want to pick k
ones with the minimum moves, using swaps and at most maxChanges
flips. The best strategy is to simulate picking at each index, using a sliding window to count nearby ones and zeros, and greedily use flips for zeros farthest from the pick index.
Approach
- For each possible pick index, simulate picking the one (if present).
- Use a sliding window of size
k
centered at the pick index to count ones and zeros. - Use up to
maxChanges
flips for zeros farthest from the pick index. - For remaining zeros, use swaps (each swap counts as a move).
- Track the minimum moves over all pick indices.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
, as we simulate for each index and sort distances. - 🧺 Space complexity:
O(n)
, for storing distances and ones.