玩筹码
难度:
标签:
题目描述
有 n
个筹码。第 i
个筹码的位置是 position[i]
。
我们需要把所有筹码移到同一个位置。在一步中,我们可以将第 i
个筹码的位置从 position[i]
改变为:
position[i] + 2
或position[i] - 2
,此时cost = 0
position[i] + 1
或position[i] - 1
,此时cost = 1
返回将所有筹码移动到同一位置上所需要的 最小代价 。
示例 1:
输入:position = [1,2,3] 输出:1 解释:第一步:将位置3的筹码移动到位置1,成本为0。 第二步:将位置2的筹码移动到位置1,成本= 1。 总成本是1。
示例 2:
输入:position = [2,2,2,3,3] 输出:2 解释:我们可以把位置3的两个筹码移到位置2。每一步的成本为1。总成本= 2。
示例 3:
输入:position = [1,1000000000] 输出:1
提示:
1 <= position.length <= 100
1 <= position[i] <= 10^9
代码结果
运行时间: 23 ms, 内存: 16.1 MB
/*
* Problem: There are n chips. The i-th chip is at position[i].
* We can move a chip from position[i] to position[i] + 2 or position[i] - 2 with cost = 0,
* or to position[i] + 1 or position[i] - 1 with cost = 1.
* Our goal is to move all chips to the same position with the minimum cost.
*
* Solution:
* - Chips on even positions can be moved to other even positions with no cost.
* - Chips on odd positions can be moved to other odd positions with no cost.
* - Thus, the optimal strategy is to move all chips to the even or odd position with the maximum count,
* and then move chips from the other group to this position with cost = 1 per chip.
*/
import java.util.Arrays;
public class Solution {
public int minCostToMoveChips(int[] position) {
long evenCount = Arrays.stream(position)
.filter(pos -> pos % 2 == 0)
.count();
long oddCount = position.length - evenCount;
return (int) Math.min(evenCount, oddCount);
}
}
解释
方法:
该题解采用的是观察所有筹码位置的奇偶性。因为筹码位置的改变只有两种情况:移动2个单位(无成本)和移动1个单位(成本为1)。移动2个单位不改变筹码的奇偶性,因此我们只需关注将筹码移动到奇数位置或偶数位置的最小成本。通过统计所有奇数位置和偶数位置的筹码数量,我们可以确定哪种筹码更多。最终,将较少的一种筹码(无论是奇数还是偶数)移动到另一种位置将产生的成本就是答案,因为每次移动成本为1。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
在算法中,你是如何确定将筹码统计为奇数位置和偶数位置的原理是什么?为什么这种分类对解决问题有效?
▷🦆
为什么将筹码从奇数位置移动到偶数位置,或者从偶数位置移动到奇数位置的成本是1,而移动两个单位的成本是0?
▷🦆
在实现代码中,`Counter(i % 2 for i in position)`是用来做什么的?这里的`i % 2`表示什么意思?
▷🦆
如果输入数组`position`中所有的筹码已经位于同一位置,算法的输出是否还是正确的?
▷