Minimum Moves to Pick K Ones - Problem
You're given a binary array nums of length n, and two integers: k (the number of ones to collect) and maxChanges (maximum flips allowed).
Alice's Mission: Collect exactly k ones using the minimum number of moves possible!
Game Rules:
- Alice starts at any index
aliceIndexshe chooses - If there's a 1 at her starting position, she picks it up for free (no move cost)
- She can perform two types of moves:
- Create a 1: Change any 0 to 1 (costs 1 move, limited to
maxChangestimes) - Swap adjacent: Swap a 1 with an adjacent 0 (costs 1 move). If the 1 moves to Alice's position, she picks it up
- Create a 1: Change any 0 to 1 (costs 1 move, limited to
Goal: Return the minimum number of moves needed to collect exactly k ones.
Example: With nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1, Alice could start at index 5, pick up that 1 for free, create a 1 at index 4 (1 move), then swap it to her position (1 move), and swap the 1 from index 6 to her position (1 move). Total: 3 moves for 3 ones.
Input & Output
example_1.py — Basic Case
$
Input:
nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1
›
Output:
3
💡 Note:
Alice can start at index 5 (has a 1), create a 1 at index 4 using maxChanges (1 move), swap it to position 5 (1 move), then swap the 1 from index 6 to position 5 (1 move). Total: 3 moves to collect 3 ones.
example_2.py — Use MaxChanges Optimally
$
Input:
nums = [0,0,0,0], k = 2, maxChanges = 3
›
Output:
4
💡 Note:
No existing ones, so Alice must create all ones using maxChanges. She can start anywhere, create a 1 at her position (1 move), pick it up (1 move), create another 1 (1 move), pick it up (1 move). Total: 4 moves for 2 ones.
example_3.py — Adjacent Ones Advantage
$
Input:
nums = [1,1,1,1,1], k = 3, maxChanges = 0
›
Output:
2
💡 Note:
Alice should start at index 2 (middle). She gets 1 one for free at her position, then can swap adjacent ones at indices 1 and 3 to her position (1 move each). Total: 2 moves for 3 ones.
Constraints
- 1 ≤ nums.length ≤ 105
- nums[i] is either 0 or 1
- 1 ≤ k ≤ nums.length
- 0 ≤ maxChanges ≤ 109
- The answer is guaranteed to exist
Visualization
Tap to expand
Understanding the Visualization
1
Choose Optimal Starting Point
Alice evaluates each position to maximize free treasures nearby
2
Collect Free Treasures
Pick up treasure at current position (free) and adjacent treasures (1 move each)
3
Use Magic Wisely
Create treasures at Alice's position using maxChanges (2 moves per treasure: create + collect)
4
Gather Remaining Treasures
Use sliding window to find closest existing treasures and minimize total swapping distance
Key Takeaway
🎯 Key Insight: The optimal strategy combines greedy local collection (adjacent ones) with strategic use of maxChanges, then applies sliding window technique to minimize the distance when collecting remaining ones from existing positions.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code