【leetcode】1217. Minimum Cost to Move Chips to The Same Position
2024-09-08 01:27:03
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
orposition[i] - 2
withcost = 0
.position[i] + 1
orposition[i] - 1
withcost = 1
.
Return the minimum cost needed to move all the chips to the same position.
Example 1:
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 2:
Input: position = [1,1000000000]
Output: 1
这道题乍一看还挺复杂,但仔细想一想还是挺简单,题目的意思是将n个chips移动到一起最小的花销,而且移动的cost有规定,如果距离差一,则移动到一起cost=1,如果距离差二,则移动到一起cost=0,这句话隐含的含义是就是,如果两个chips之间距离为偶数的话,则cost=0,就可以移动到一起。如果距离是奇数的话,移动到一起cost=1。这样的话就可以将所有chips分成两组,奇数组和偶数组,然后将二者中chips个数小的往chips个数较多的移动即可,简而言之就是输出二者的最小值。
class Solution {
public:
int minCostToMoveChips(vector<int>& position) {
// 如果位置之间的差距是2的倍数 则可以化为一类
// 如果位置之间的差距是奇数则 则差距为1
// 所以可以将所有位置拆分为奇数 或者偶数
// 奇数position 移动到1 的cost 都为0 偶数position 移动到2 的cost 都为0
int dp[2]={0};
for(auto pp:position){
if(pp&1==1){
dp[1]+=1;
}
else{
dp[0]+=1;
}
}
return min(dp[0],dp[1]);
}
};
最新文章
- Android自定义View初步
- 2016年11月24日--面向对象、C#小复习
- SQL --Chater03 聚合与排序
- protobuf C++ 使用示例
- android之网络操作(1)
- linux点滴:rsync
- struts2接收参数——域模型、DTO
- Linux_hadoop_install
- ASP.NET页面上传文件时提示文件大小超过请求解决方法
- iscroll.js实现上拉刷新,下拉加载更多,应用技巧项目实战
- 对只转发结果集的无效操作:provious()
- @ConfigurationProperties + @EnableConfigurationProperties
- Zookeeper 在Windows下的安装过程及测试
- seleium 鼠标悬停事件
- BZOJ2152 [国家集训队] 聪聪可可 [点分治]
- start-stop-daemon自动启动、关闭后台程序参数传递
- oracle charset
- 30、Arrays工具类
- qbxt Day1 测试犯傻祭祀
- 使用SpringMVC解决Ajax跨域问题
热门文章
- hdu 1394 Minimum Inversion Number(线段树or树状数组)
- poj 2724 Purifying Machine(二分图最大匹配)
- js和jq文档操作
- mysql 导入sql文件
- The art of multipropcessor programming 读书笔记-3. 自旋锁与争用(2)
- 解决虚拟机安装linux系统无法全屏问题 &; vmtools安装
- #web开发# 知道cookie hostonly属性的请举手。
- 低代码开发,推荐一款Web 端自动化神器:Automa
- Linux——搭建Apache(httpd)服务器
- [noi32]sort