[LeetCode] Minimum Cost to Move Chips to The Same Position

아르당·약 19시간 전

LeetCode

목록 보기
254/254
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

n개 칩을 가지고 있고, i번째 칩의 위치는 position[i]이다.
모든 칩을 같은 위치로 이동시켜야 한다. 한 단계마다 i번째 칩의 위치를 position[i]에서 다른 위치로 바꿀 수 있다.

  • position[i] + 2 or position[i] - 2 with cost = 0.
  • position[i] + 1 or position[i] - 1 with cost = 1.

모든 칩을 같은 위치로 옮기는 데 필요한 최소 비용을 반환해라.

Example

#1

Input: position = [1, 2, 3]
Output: 1
Explanation:
1단계: 위치 3에 있는 칩을 비용 0으로 위치 1로 옮긴다.
2단계: 위치 2에 있는 칩을 비용 1로 위치 1로 옮긴다.
총 비용은 1이다.

#2

Input: position = [2, 2, 2, 3, 3]
Output: 2
Explanation: 위치 3에 있는 칩 2개를 위치 2로 옮긴다. 각 이동의 비용은 1이다. 총 비용은 2이다.

#3
Input: position = [1, 1000000000]
Output: 1

Constraints

  • 1 <= position.length <= 100
  • 1 <= position[i] <= 10^9

Solved

class Solution {
    public int minCostToMoveChips(int[] position) {
        int evenCount = 0;
        int oddCount = 0;

        for(int p : position){
            if(p % 2 == 0){
                evenCount++;
            }else{
                oddCount++;
            }
        }

        return Math.min(oddCount, evenCount);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글