leetcode 1217. play chips

Problem description :
There are n chips. The position of the i-th chip is position[i].

We need to move all chips to the same position. In one step, we can change the position of the i-th chip from position[i] to:

position[i] + 2 or position[i] - 2, at this time cost = 0
position[i] + 1 or position[i] - 1, at this time cost = 1
returns the cost required to move all chips to the same position minimum cost.

Example :
Input: position = [1,2,3]
Output: 1
Explanation: Step 1: Move the chip at position 3 to position 1 with a cost of 0.
Step 2: Move the chip from position 2 to position 1, cost = 1.
The total cost is 1.

Solution : Using the idea of ​​a greedy algorithm, after analyzing the problem, we found that the cost of moving from an even number to an even number is 0. The same goes for moving from an odd number to an odd number. Only the movement from an even number to an odd number or an odd number to an even number requires a cost of 1. So if we want to minimize the total cost, we can directly find the sum of the even numbers and the sum of the odd numbers, and compare which one is smaller, then the cost will be the smaller value.

from collections import Counter
class Solution:
    def minCostToMoveChips(self, position: List[int]) -> int:
        #统计余数为1的个数,和余数为0的个数
        cnt = Counter(p%2 for p in position)
        return min(cnt[0],cnt[1])

refer: Detailed explanation of Counter() of Python collections module

Supongo que te gusta

Origin blog.csdn.net/Rolandxxx/article/details/128361709
Recomendado
Clasificación