Minimum Cost to Move Chips to The Same Position
Problem
You have n chips on integer positions. A move of ±2 costs 0; a move of ±1 costs 1. Return the minimum total cost to stack all chips on the same position.
position = [2, 2, 2, 3, 3]2def min_cost_to_move_chips(position):
even = sum(1 for p in position if p % 2 == 0)
odd = len(position) - even
return min(even, odd)
function minCostToMoveChips(position) {
let even = 0, odd = 0;
for (const p of position) (p % 2 === 0 ? even++ : odd++);
return Math.min(even, odd);
}
class Solution {
public int minCostToMoveChips(int[] position) {
int even = 0, odd = 0;
for (int p : position) {
if (p % 2 == 0) even++; else odd++;
}
return Math.min(even, odd);
}
}
int minCostToMoveChips(vector<int>& position) {
int even = 0, odd = 0;
for (int p : position) (p % 2 == 0 ? even++ : odd++);
return min(even, odd);
}
Explanation
The key insight is that a move of ±2 is free. So a chip can hop to any position of the same parity (even or odd) without paying anything at all.
That means every chip on an even position can gather together for free, and every chip on an odd position can gather together for free. We really only have two piles: even chips and odd chips.
To stack everything on one spot, we move one whole pile across to join the other. Each chip in the pile we move costs exactly 1 (a single ±1 step changes its parity), so the total cost is just the size of the smaller pile.
The code counts how many positions are even, the rest are odd, and returns min(even, odd).
Example: [2,2,2,3,3] has 3 even chips and 2 odd chips. Moving the 2 odd chips over costs 1 each, so the answer is 2.