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

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:

Example 1

Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
Second step: Move the chip at position 2 to position 1 with cost = 1.
Total cost is 1.

Example 2:

Example 2

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 3:
Input: position = [1,1000000000]
Output: 1

Constraints:

  • 1 <= position.length <= 100
  • 1 <= position[i] <= 10^9

Solution:

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

In fact, we can move all chips at even positions to position 0, and move all chips at the odd positions to position 1. Then, we only have many chips at position 0 and other chips at position 1. Next, we only need to move those two piles together. Given two piles of chips located at 0 and 1 respectively, intuitively it would be less effort-taking (i.e. less cost) to move the smaller pile to the larger one, which makes the total cost to the minimum of even count and odd count.
实际上,我们可以将所有chip移动到偶数位置,并将所有chip移动到奇数位置,然后移至位置1。然后,我们只有很多chip位于位置0,其他chip位于位置1。接下来,我们只需要一起移动两堆中的一堆到另一堆。直观地讲,将较小的堆移动到较大的堆将花费更少的精力(即更少的成本),这使总成本为偶数chip和奇数chip中的最小值。

你可能感兴趣的:(LeetCode 1217. Minimum Cost to Move Chips to The Same Position (Easy))