Minimum Cost to Move Chips to The Same Position

easy math greedy

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.

Inputposition = [2, 2, 2, 3, 3]
Output2
3 chips on even positions, 2 on odd. Move the 2 odd ones at cost 1 each → 2.

def 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);
}
Time: O(n) Space: O(1)