[Leetcode] 1217. Minimum Cost to Move Chips to The Same Position (C++)

마이구미·2021년 12월 6일
0

PS

목록 보기
54/69
post-thumbnail

문제

1217. Minimum Cost to Move Chips to The Same Position

코드

class Solution {
public:
    int minCostToMoveChips(vector<int>& position) {
        int even = 0, odd = 0;
        for (int p : position){
            if (p%2) odd++;
            else even++;
        }
        return min(even, odd);
    }
};

접근

2칸을 움직일 때는 cost가 0, 1칸을 움직일 때는 cost가 1이다. 따라서 홀수칸 끼리, 짝수칸 끼리 움직임은 cost에 영향을 주지 않는다. 결과적으로 한 곳에 모아야하기 때문에 짝수, 홀수에 위치한 개수가 영향을 준다. 그래서 각각의 개수를 구하고 작은 값을 반환했다.

profile
마이구미 마시쪙

0개의 댓글