Minimum Cost to Move Chips to The Same Position - Problem
Imagine you have n poker chips scattered across different positions on a number line. Your goal is to gather all chips at the same position with minimal cost.
You have two types of moves available:
- Free moves: Move a chip 2 positions left or right (
position ± 2) at zero cost - Costly moves: Move a chip 1 position left or right (
position ± 1) at cost = 1
Given an array position where position[i] represents the location of the i-th chip, return the minimum cost needed to move all chips to the same position.
Key insight: Since moving 2 positions is free, you can think of positions as either "even" or "odd". Moving between even positions (or between odd positions) costs nothing, but moving from even to odd (or vice versa) costs exactly 1.
Input & Output
example_1.py — Basic Case
$
Input:
position = [1,2,3]
›
Output:
1
💡 Note:
Move chip at position 2 to position 1 (cost 1) or position 3 (cost 1). All other moves are free since they involve ±2 steps. Even positions: 1 chip at 2, Odd positions: 2 chips at 1,3. Answer = min(1,2) = 1
example_2.py — All Same Parity
$
Input:
position = [2,2,2,3,3]
›
Output:
2
💡 Note:
Even positions: 3 chips at position 2. Odd positions: 2 chips at position 3. To gather all chips, move the 2 odd chips to even positions (each costs 1). Answer = min(3,2) = 2
example_3.py — Single Chip
$
Input:
position = [1]
›
Output:
0
💡 Note:
Only one chip, so it's already gathered at one position. No moves needed. Answer = 0
Constraints
- 1 ≤ chips.length ≤ 100
- 1 ≤ chips[i] ≤ 109
- Note: The large constraint on position values (up to 109) hints that we shouldn't iterate through all positions
Visualization
Tap to expand
Understanding the Visualization
1
Understand Movement Costs
±2 moves are free, ±1 moves cost 1. This means switching between even/odd parity always costs exactly 1.
2
Group by Parity
Separate chips into even and odd position groups. Within each group, all chips can reach each other for free.
3
Choose Strategy
Either move all even chips to odd positions, or vice versa. Choose the cheaper option.
4
Calculate Result
The minimum cost is always min(even_count, odd_count).
Key Takeaway
🎯 Key Insight: Since ±2 moves are free, positions are essentially either 'even type' or 'odd type'. The minimum cost is always the count of the minority group.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code