leetcode 1217. Play with Chips 解法 python

本文介绍了一种算法,用于计算将所有芯片移动到同一位置所需的最小成本。通过分析奇数和偶数位置的芯片,我们发现只需考虑移动一步的次数,即可找到最优解。文章详细解释了解决方案,并提供了Python代码实现。

一.问题描述

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:

  • Move the i-th chip by 2 units to the left or to the right with a cost of 0.
  • Move the 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).

 

Example 1:

Input: chips = [1,2,3]
Output: 1
Explanation: Second chip will be moved to positon 3 with cost 1. First chip will be moved to position 3 with cost 0. Total cost is 1.

Example 2:

Input: chips = [2,2,2,3,3]
Output: 2
Explanation: Both fourth and fifth chip will be moved to position two with cost 1. Total minimum cost will be 2.

 

Constraints:

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

二.解决思路

这道题的意思就是我们要将所有的署条移动到同一个位置,移动两步不需要cost,移动一步要1cost

首先我们需要意识到的一点是:

把所有位置在奇数的署条移动到同一个奇数位置不需要cost,因为每次都是移动2步

偶数位置的署条也一样

例如: chips=[1,3,5,7,9]

把chips转化成[1,1,1,1,1]并不需要cost,因为对每个位置来说他们都是移动2n步

因此,要计算最小的cost,我们只需要关注有多少个移动1步的步骤

最小的移动步骤出现在所有的奇数位置chips都与所有偶数位置的chips相邻的情况

因为如果不相邻,我们可以一直移动两步使他们相邻,cost为0

可以想象以下,

首先,我们可以把所有奇数位置的chip移动到位置x,这一步cost为0

然后,我们可以把所有偶数位置的chip移动到毗邻x的位置(x-1 或者 x+1,这两个数必然是偶数),cost为0

此时,就是最小的cost出现的情况,问题转化为计算偶数位置chips的数量和奇数位置chips的数量,最小的那个即为最小的cost(将较小数量的那堆chips移动到较大的那一堆)。

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起套路一起刷题一起ac

三.源码

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

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值