1.문제
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.
각 칩의 위치정보 배열 position이 주어질 때 현재 위치에서 +- 2 움직이는 것은 cost 0,
+- 1 움직이는것은 cost 1 일 때 가장 적은 cost로 칩을 한곳으로 모으는 경우를 리턴하는 문제이다.
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.
Total cost is 1.
Example 2

Input: position = [2,2,2,3,3]
Output: 2
Explanation: We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.
Example 3
Input: position = [1,1000000000]
Output: 1
Constraints:
- 1 <= position.length <= 100
- 1 <= position[i] <= 10^9
2.풀이
- 양옆으로 2씩 움직이는 것은 cost가 들지않으므로 짝수자리에 있는 칩은 2로 , 홀수자리 칩은 1로 cost없이 모을 수 있다.
- 양옆으로 1씩 움직이는 것은 cost가 1이므로 짝수자리에 있는 칩들과 홀수 자리에 있는 칩들 중 갯수가 작은 값의 칩을 한쪽으로 옮기면 된다.
/**
* @param {number[]} position
* @return {number}
*/
const minCostToMoveChips = function (position) {
let even = 0;
let odd = 0;
position.forEach((item) => {
// 짝수면 even++ , 홀수면 odd++
item % 2 === 0 ? even++ : odd++;
});
return Math.min(even, odd);
};
3.결과
