-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1167. Minimum Cost to Connect Sticks (Greedy with Heap) 20.5.22 Medium
More file actions
53 lines (46 loc) · 1.57 KB
/
1167. Minimum Cost to Connect Sticks (Greedy with Heap) 20.5.22 Medium
File metadata and controls
53 lines (46 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
You have some sticks with positive integer lengths.
You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y.
You perform this action until there is one stick remaining.
Return the minimum cost of connecting all the given sticks into one stick in this way.
Solution: --------------------------------------- my own ---------------------- Greedy with Heap
------------------------------------------------- O(nlogn) T, O(n) S
'''
Some of the sticks will be used more than the others. Which sticks should be used the most/least?
The sticks with long lengths cost a lot so we should use these the least.
What if we keep merging the two shortest sticks?
'''
class Solution(object):
def connectSticks(self, sticks):
"""
:type sticks: List[int]
:rtype: int
"""
if not sticks:
return None
heapq.heapify(sticks)
res = 0
while len(sticks) >= 2:
merge_1 = heapq.heappop(sticks)
merge_2 = heapq.heappop(sticks)
res += merge_1 + merge_2
heapq.heappush(sticks, merge_1 + merge_2)
return res
C++ Version:
class Solution {
public:
int connectSticks(vector<int>& sticks) {
priority_queue<int, vector<int>, greater<int>> pq (sticks.begin(), sticks.end());
int x {};
int y {};
int cost {};
while (pq.size() >= 2) {
x = pq.top();
pq.pop();
y = pq.top();
pq.pop();
cost += x + y;
pq.push(x + y);
}
return cost;
}
};