有 n 个筹码。第 i 个筹码的位置是 position[i] 。
我们需要把所有筹码移到同一个位置。在一步中,我们可以将第 i 个筹码的位置从 position[i] 改变为:
position[i] + 2 或 position[i] - 2 ,此时 cost = 0
position[i] + 1 或 position[i] - 1 ,此时 cost = 1
返回将所有筹码移动到同一位置上所需要的 最小代价 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-cost-to-move-chips-to-the-same-position
- 如果奇偶性相同的两个位置,总的消耗就是0,否则就是1;
- 对每个位置进行消耗统计,取最小的就是答案了。
class Solution {
public int minCostToMoveChips(int[] position) {
int i,j;
int minCost = 100;
for(i = 0;i < position.length;i++){
int cost = 0;
for(j = 0;j < position.length; j++){
if(((position[i]-position[j]) & 1) == 1){
// 奇数++
cost++;
}
}
minCost = Math.min(minCost,cost);
}
return minCost;
}
}
巧妙解法
这题其实就是统计奇数的筹码多还是偶数的筹码多,毕竟奇偶性相同的两个位置消耗是0。如果奇数位置的筹码多,那就先把奇数位置的筹码都搬到一起,然后把偶数的搬过来就好了,总消耗就是偶数筹码的数量。
class Solution {
public int minCostToMoveChips(int[] position) {
int odd = 0;
int even = 0;
for (int i = 0; i < position.length; i++) {
if ((position[i] & 1) == 1) {
odd++;
} else {
even++;
}
}
return Math.min(odd, even);
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)