Skip to content

Commit f5de2ee

Browse files
author
Partho Biswas
committed
1167_Minimum_Cost_to_Connect_Sticks
1 parent 0b56de4 commit f5de2ee

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,7 @@ I have solved quite a number of problems from several topics. See the below tabl
322322
|15| **[378. Kth Smallest Element in a Sorted Matrix](https://tinyurl.com/shz4289)** | [Python](https://tinyurl.com/wu6rdaw/378_Kth_Smallest_Element_in_a_Sorted_Matrix.py)| [educative.io](https://tinyurl.com/scbjgjd) | Hard | 📌 TODO: Check again the Binary Search approach. Very important |
323323
|16| **[632. Smallest Range Covering Elements from K Lists](https://tinyurl.com/v3fshwo)** | [Python](https://tinyurl.com/wu6rdaw/632_Smallest_Range_Covering_Elements_from_K_Lists.py)| [educative.io](https://tinyurl.com/ubfua7f) | Hard | 📌 TODO: Check again. Very important |
324324
|17| **[846. Hand of Straights](https://tinyurl.com/y2hfqqsv)** | [Python](https://tinyurl.com/wu6rdaw/846_Hand_of_Straights.py)| **[Art 1](https://tinyurl.com/w8pkf55)** | Medium | 📌 TODO: Check again. Very important |
325+
|18| **[1167. Minimum Cost to Connect Sticks](https://tinyurl.com/y8s5s8pq)** | [Python](https://tinyurl.com/wu6rdaw/1167_Minimum_Cost_to_Connect_Sticks.py)| | Medium | |
325326

326327
</p>
327328
</details>
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import heapq
2+
3+
class Solution(object):
4+
def connectSticks(self, sticks):
5+
"""
6+
:type sticks: List[int]
7+
:rtype: int
8+
"""
9+
sticksHeap = list(sticks)
10+
heapq.heapify(sticksHeap)
11+
minCost = 0
12+
while len(sticksHeap) > 1:
13+
firstNum = heapq.heappop(sticksHeap)
14+
secondNum = heapq.heappop(sticksHeap)
15+
minCost += firstNum
16+
minCost += secondNum
17+
sumNum = firstNum + secondNum
18+
heapq.heappush(sticksHeap, sumNum)
19+
return minCost
20+
21+
22+
"""
23+
Example 1
24+
sticks = [2,4,3]
25+
26+
Step 1:
27+
cost -> 2+3 = 5
28+
result -> [5,4]
29+
30+
Step 2:
31+
cost -> 5+4 = 9
32+
result -> [9]
33+
34+
FINAL COST =5 + 9 = 14
35+
36+
2,4=6
37+
>6,3=9
38+
39+
6+9=15
40+
"""

0 commit comments

Comments
 (0)