Skip to main content
Back to problems
#1217
Easy Algorithms

Minimum cost to move chips to the same position

Array Math Greedy
72.8% acceptance
Feb 25, 2026
2454
349
We have n chips, where the position of the ith 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 ith 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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_cost_to_move_chips(position: Vec<i32>) -> i32 {
    // Moving by 2 is free; moving by 1 costs 1.
    // All even-position chips can be moved to any even position for free.
    // All odd-position chips can be moved to any odd position for free.
    // Moving between odd and even costs 1 per chip.
    let even = position.iter().filter(|&&x| x % 2 == 0).count() as i32;
    let odd = position.iter().filter(|&&x| x % 2 != 0).count() as i32;
    even.min(odd)
  }
}