LeetCode 1217 Minimum Cost to Move Chips to The Same Position (Python)

Posted by 小明MaxMing on November 5, 2020

题目

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.

解题思路

奇数移动到奇数,偶数移动到偶数花费是0,奇数偶数相互移动花费是1,结果是全移动到奇数,或全移动到偶数,所以结果为,奇数和偶数中少的

代码

class Solution:
    def minCostToMoveChips(self, position: List[int]) -> int:
        even = 0
        for c in position:
            if c % 2 == 0:
                even += 1
        return min(even, len(position) - even)

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅