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
这题很有意思,看起来是个难题,实际上是一个脑筋急转弯,想出来非常简单。
首先移动2步,则代价为0,移动1步,则代价为1。在此基础上,无论有多少硬币,我们都将其移动到两个格子上,一个格子上存奇数,一个上面存偶数。
然后我们只要看哪个小即可,就这么简单直接。
class MinimumCostToMoveChipsToTheSamePosition : public Solution {
public:
void Exec() {
}
int minCostToMoveChips(vector<int>& position) {
int poses[2] = {0};
for (auto i : position) {
poses[i % 2]++;
}
return poses[0] < poses[1] ? poses[0] : poses[1];
}
};