Minimum Cost to Move Chips to The Same Position - Problem

We have n chips, where the position of the i-th chip is position[i]. We need to move all the chips to the same position.

In one step, we can change the position of the i-th chip from position[i] to:

  • position[i] + 2 or position[i] - 2 with cost = 0
  • position[i] + 1 or position[i] - 1 with cost = 1

Return the minimum cost needed to move all the chips to the same position.

Input & Output

Example 1 — Mixed Positions
$ Input: position = [1,2,3]
Output: 1
💡 Note: Odd positions: 1,3 (count=2). Even positions: 2 (count=1). Move 1 chip from even to odd or vice versa, cost = min(2,1) = 1.
Example 2 — Same Parity
$ Input: position = [2,2,2,3,3]
Output: 2
💡 Note: Even positions: 2,2,2 (count=3). Odd positions: 3,3 (count=2). Move 2 chips from odd to even positions, cost = min(3,2) = 2.
Example 3 — All Same Position
$ Input: position = [1,1000000000]
Output: 1
💡 Note: One odd (1), one even (1000000000). Need to move 1 chip to change its parity, cost = min(1,1) = 1.

Constraints

  • 1 ≤ position.length ≤ 100
  • 1 ≤ position[i] ≤ 109

Visualization

Tap to expand
Minimum Cost to Move Chips INPUT 1 2 3 C1 C2 C3 Odd position Even position position = [1, 2, 3] 3 chips at positions 1,2,3 Movement Rules: +/-2 steps = cost 0 +/-1 step = cost 1 ALGORITHM STEPS 1 Key Observation Move by 2: same parity, cost=0 2 Count Parities Odd: pos 1,3 --> count=2 Even: pos 2 --> count=1 3 Strategy Move all to same parity: FREE Then move minority group 4 Calculate Min Cost cost = min(odd, even) cost = min(2, 1) = 1 Odd: 2 Even: 1 min(2,1) = 1 FINAL RESULT 1 2 3 C1 C2 C3 C1: stays at 1 (cost=0) C2: 2-->1 (cost=1) C3: 3-->1 (cost=0) Output: 1 Total Cost = 0 + 1 + 0 = 1 OK - Optimal! Key Insight: Moving a chip by 2 positions costs nothing and preserves parity (odd/even). All chips at odd positions can be moved to any odd position for free, same for even. The minimum cost is simply the count of the minority group (either odd or even count), as only those need a single +/-1 step to change parity. TutorialsPoint - Minimum Cost to Move Chips to The Same Position | Optimal Solution
Asked in
Google 15 Amazon 12 Facebook 8
25.0K Views
Medium Frequency
~10 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen