标签:imu sam play cto and initial eve nbsp 思路
There are some chips, and the i-th chip is at position chips[i]
.
You can perform any of the two following types of moves any number of times (possibly zero) on any chip:
i
-th chip by 2 units to the left or to the right with a cost of 0.i
-th chip by 1 unit to the left or to the right with a cost of 1.There can be two or more chips at the same position initially.
Return the minimum cost needed to move all the chips to the same position (any position).
思路:
要把 j 位置的薯片移到 i 位置,cost只看两者的距离是奇数还是偶数。偶数,则cost为0;奇数,不管要移多少都可以看作是移2k+1 ,cost是1.
又,偶数和偶数相减是偶数,奇数和奇数相减也是偶数,所以,只有将奇数位置的薯片移到偶数位置才会有cost。
要全部都移到一个位置,那么就要考虑将所有偶数位置移到奇数的cost(为偶数的个数),或者所有奇数移到偶数的cost(为奇数的个数),跟具体移到哪里没有关系。
所以,只要看数组元素是偶数少还是奇数少,取少的那一个就是最小cost。
class Solution { public: int minCostToMoveChips(vector<int>& chips) { int odd=0,even=0; for(int i=0;i<chips.size();i++){ if(chips[i]%2) odd++; else even++; } return odd<even?odd:even; } };
【算法】 LEETCODE 1217. Play with Chips
标签:imu sam play cto and initial eve nbsp 思路
原文地址:https://www.cnblogs.com/rarecu/p/11631997.html