반응형
LV. Easy 😎
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/
문제
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.
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
문제 해결법
짝수에서 짝수, 홀수에서 홀수로 옮기는 건 cost가 들지 않기 때문에 position의 짝수 개수와 홀수 개수를 알면 문제 해결 가능!
짝수 개수 > 홀수 개수이면 임의의 짝수에 홀수를 옮기는 게 cost가 제일 적게 듦으로 minimum cost는 홀수 개수.
짝수 개수 < 홀수 개수이면 임의의 홀수에 짝수를 옮기는 게 cost가 제일 적게 듦으로 minimum cost는 짝수 개수.
해결 코드
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int minCostToMoveChips(vector<int> &position) {
int even_cost = 0;
int odd_cost = 0;
for (int i = 0; i < position.size(); ++i) {
if (position[i] % 2 == 0)
odd_cost++;
else
even_cost++;
}
return odd_cost > even_cost ? even_cost : odd_cost;
}
};
int main() {
Solution sol;
vector<int>a;
a.push_back(1);
a.push_back(100000);
// a.push_back(3);
// a.push_back(3);
// a.push_back(3);
cout << sol.minCostToMoveChips(a) << endl;
}
728x90
'Computer Science > 알고리즘' 카테고리의 다른 글
leetcode 416) Partition Equal Subset Sum (0) | 2022.01.04 |
---|---|
leetcode 221) Maximal Square (0) | 2022.01.04 |
leetcode 878) Nth Magical Number (0) | 2022.01.03 |
leetcode 790) Domino and Tromino Tiling (0) | 2022.01.02 |
LeetCode 476) Number Complement (0) | 2021.12.30 |
댓글