You have some number of sticks with positive integer lengths. These lengths are given as an array
sticks[i] is the length of the
You can connect any two sticks of lengths
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.
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 = . There is only one stick left, so you are done. The total cost is 5 + 9 = 14.
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 = . There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30.
Input: sticks =  Output: 0 Explanation: There is only one stick, so you don't need to do anything. The total cost is 0.
1 <= sticks.length <= 104
1 <= sticks[i] <= 104
import heapq class Solution(object): def connectSticks(self, sticks): """ :type sticks: List[int] :rtype: int """ heapq.heapify(sticks) total = 0 while len(sticks) > 1: stick0 = heapq.heappop(sticks) stick1 = heapq.heappop(sticks) cost = stick0 + stick1 total += cost heapq.heappush(sticks, cost) return total
- We need to combine everything anyway, thus always sticks currently 2 smallest ones
- Best data structure for this purpose is
class Solution: def connectSticks(self, sticks: List[int]) -> int: n, heap = len(sticks), sticks heapq.heapify(heap) ans = 0 for i in range(n-1): s = heapq.heappop(heap) + heapq.heappop(heap) heapq.heappush(heap, s) ans += s return ans
A really cool feature of python heap is
heapq.heapreplace. It’s more efficient than
heapq.heappop + heapq.heappush, below is an example