【算法】 LEETCODE 1217. Play with Chips

时间:2019-10-07 21:09:54   收藏:0   阅读:87

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:

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;
    }
};

 

原文:https://www.cnblogs.com/rarecu/p/11631997.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!