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 = [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]);
}
};

最新文章

  1. Android自定义View初步
  2. 2016年11月24日--面向对象、C#小复习
  3. SQL --Chater03 聚合与排序
  4. protobuf C++ 使用示例
  5. android之网络操作(1)
  6. linux点滴:rsync
  7. struts2接收参数——域模型、DTO
  8. Linux_hadoop_install
  9. ASP.NET页面上传文件时提示文件大小超过请求解决方法
  10. iscroll.js实现上拉刷新,下拉加载更多,应用技巧项目实战
  11. 对只转发结果集的无效操作:provious()
  12. @ConfigurationProperties + @EnableConfigurationProperties
  13. Zookeeper 在Windows下的安装过程及测试
  14. seleium 鼠标悬停事件
  15. BZOJ2152 [国家集训队] 聪聪可可 [点分治]
  16. start-stop-daemon自动启动、关闭后台程序参数传递
  17. oracle charset
  18. 30、Arrays工具类
  19. qbxt Day1 测试犯傻祭祀
  20. 使用SpringMVC解决Ajax跨域问题

热门文章

  1. hdu 1394 Minimum Inversion Number(线段树or树状数组)
  2. poj 2724 Purifying Machine(二分图最大匹配)
  3. js和jq文档操作
  4. mysql 导入sql文件
  5. The art of multipropcessor programming 读书笔记-3. 自旋锁与争用(2)
  6. 解决虚拟机安装linux系统无法全屏问题 &amp; vmtools安装
  7. #web开发# 知道cookie hostonly属性的请举手。
  8. 低代码开发,推荐一款Web 端自动化神器:Automa
  9. Linux——搭建Apache(httpd)服务器
  10. [noi32]sort