### LeetCode - Minimum Cost to Move Chips to The Same Position Solution - The Coding Shala

Home >> LeetCode >> Minimum Cost to Move Chips to The Same Position

In this post, we will learn how to solve LeetCode's Minimum Cost to Move Chips to The Same Position problem and will implement its solution in Java.

## Minimum Cost to Move Chips to The Same Position Problem

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.

Example 1:
Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0. Second step: Move the chip at position 2 to position 1 with cost = 1. The total cost is 1.

Example 2:
Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0. Second step: Move the chip at position 2 to position 1 with cost = 1. The total cost is 1.

## Minimum Cost to Move Chips to The Same Position Java Solution

Approach 1:
Moving the chips to position[i]+2 and position[i]-2 will cost 0, so we will move all the even position chips at 0 position and odd position chips at 1 index. Whichever pile is less will return that count.

Java Program:

```class Solution {
public int minCostToMoveChips(int[] position) {
int even = 0;
int odd = 0;
for(int i=0; i<position.length; i++) {
if(position[i]%2 == 0) {
even++;
} else {
odd++;
}
}
return (even < odd) ? even : odd;
}
}
```

Other Posts You May Like