#3086
Minimum Moves to Pick K Ones
HardArrayGreedySliding WindowPrefix SumSliding WindowPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a sliding window approach combined with prefix sums to efficiently calculate the minimum moves required to collect k ones. This method reduces unnecessary checks and focuses on the most promising segments of the array.
⚙️
Algorithm
3 steps- 1Step 1: Create a prefix sum array to count the number of ones in the original array.
- 2Step 2: Use a sliding window of size k to find the best segment of k ones, calculating the moves needed to convert zeros to ones within this window.
- 3Step 3: For each window, calculate the number of moves required, considering the maxChanges allowed.
solution.py13 lines
1def minMoves(nums, k, maxChanges):
2 n = len(nums)
3 prefix_sum = [0] * (n + 1)
4 for i in range(n):
5 prefix_sum[i + 1] = prefix_sum[i] + nums[i]
6 min_moves = float('inf')
7 for i in range(n - k + 1):
8 ones_in_window = prefix_sum[i + k] - prefix_sum[i]
9 zeros_in_window = k - ones_in_window
10 moves = zeros_in_window + (ones_in_window - 1)
11 if zeros_in_window <= maxChanges:
12 min_moves = min(min_moves, moves)
13 return min_movesℹ
Complexity note: The prefix sum array allows us to quickly calculate the number of ones in any window of size k, leading to linear time complexity.
- 1Using a sliding window helps to efficiently find the best segment of k ones.
- 2Prefix sums allow for quick calculations of the number of ones in any segment.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.