1.题目
2.题解
2.1 暴力解
2.2 数学规律
数轴上放置了一些筹码,每个筹码的位置存在数组 chips 当中。
你可以对 任何筹码 执行下面两种操作之一(不限操作次数,0 次也可以):
最开始的时候,同一位置上也可能放着两个或者更多的筹码。
返回将所有筹码移动到同一位置(任意位置)上所需要的最小代价。
示例:
输入:chips = [1,2,3]
输出:1
解释:第二个筹码移动到位置三的代价是 1,第一个筹码移动到位置三的代价是 0,总代价为 1。
输入:chips = [2,2,2,3,3]
输出:2
解释:第四和第五个筹码移动到位置二的代价都是 1,所以最小总代价为 2。
提示:
1 <= chips.length <= 100
1 <= chips[i] <= 10^9
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/play-with-chips
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
假设均移到位置p,则与p距离为奇数的代价为1,偶数为0。
public class Solution1217 {
@Test
public void test1217() {
int[] chips = {2, 2, 2, 3, 3};
System.out.println(minCostToMoveChips(chips));
}
public int minCostToMoveChips(int[] chips) {
Map map = new HashMap<>();
for (int chip : chips) {
map.put(chip, map.getOrDefault(chip, 0) + 1);
}
int result = Integer.MAX_VALUE;
for (int chip : map.keySet()) {
int t = 0;
for (int chip1 : map.keySet()) {
t += map.get(chip1) * (Math.abs((chip1 - chip)) % 2);
}
result = Math.min(result, t);
}
return result;
}
}
事实上,
故最小代价为Min(奇数位置数量, 偶数位置数量),
public class Solution1217 {
@Test
public void test1217() {
int[] chips = {2, 2, 2, 3, 3};
System.out.println(minCostToMoveChips(chips));
}
public int minCostToMoveChips(int[] chips) {
int odd = 0, even = 0;
for (int chip : chips) {
if (chip % 2 == 0) {
even++;
} else {
odd++;
}
}
return Math.min(odd, even);
}
}