LeetCode 1167. Minimum Cost to Connect Sticks - 亚马逊高频题19

给定n根棍子,每根棍子长度不一。将它们连接成一根棍子的最小成本是每次选取两根最短的棍子并连接,直至只剩一根。文章通过贪心算法,利用最小堆实现这一过程,求解最小连接成本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick.

You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining.

Return the minimum cost of connecting all the given sticks into one stick in this way.

Example 1:

Input: sticks = [2,4,3]
Output: 14
Explanation: You start with sticks = [2,4,3].
1. Combine sticks 2 and 3 for a cost of 2 + 3 = 5. Now you have sticks = [5,4].
2. Combine sticks 5 and 4 for a cost of 5 + 4 = 9. Now you have sticks = [9].
There is only one stick left, so you are done. The total cost is 5 + 9 = 14.

Example 2:

Input: sticks = [1,8,3,5]
Output: 30
Explanation: You start with sticks = [1,8,3,5].
1. Combine sticks 1 and 3 for a cost of 1 + 3 = 4. Now you have sticks = [4,8,5].
2. Combine sticks 4 and 5 for a cost of 4 + 5 = 9. Now you have sticks = [9,8].
3. Combine sticks 9 and 8 for a cost of 9 + 8 = 17. Now you have sticks = [17].
There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30.

Example 3:

Input: sticks = [5]
Output: 0
Explanation: There is only one stick, so you don't need to do anything. The total cost is 0.

Constraints:

  • 1 <= sticks.length <= 104
  • 1 <= sticks[i] <= 104

题目给定一个长度为n的数组sticks表示有n根棍子,sticks[i]表示第i根棍子的长度。每次可以任意挑选两根棍子连在一起,假定它们的长度分别为x和y,那么花费就是x+y。现在要求以最少的花费把所有棍子连成一根棍子,问最少花费应该是多少。

根据题意,花费是由棍子长度决定的,棍子越长花费越多。另外两根棍子连在一起后,还需要跟后面的棍子连在一起,也就是说先被挑中连接的棍子,将会在后面再次跟其它棍子相连接,它们的花费也将会被累加。本着贪心法则,我们当然希望长的棍子花费尽量少地被累加,因此我们应该每次先挑最短的两根相连,尽可能地把长的棍子留到后面。

总是要从一组数中挑选最小值,最容易想到的就是优先级队列(最小堆)。把所有棍子的长度值放入一个最小堆中,那么每次从最小堆弹出的两个就是最短的两根棍子,连在一起后把总花费计入结果,然后再把连在一起的新棍子的长度值放回到最小堆里。重复这样操作,直到最小堆里只剩下一个值,即所有棍子都被连在了一起形成一根长棍子。

class Solution:
    def connectSticks(self, sticks :List[int]) -> int:
        res = 0
        heapq.heapify(sticks)
        while len(sticks) > 1 :
            s = heapq.heappop(sticks)
            s += heapq.heappop(sticks)
            heapq.heappush(sticks, s)
            res += s
        return res
            

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值