Skip to content

Commit b21a942

Browse files
committed
Solved problem 1046 : Last Stone Weight
1 parent 58b9d07 commit b21a942

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* Problem: 1046
3+
* Name: Last Stone Weight
4+
* Difficulty: Easy
5+
* Topic: Priority Queue
6+
* Link: https://leetcode.com/problems/last-stone-weight/
7+
*/
8+
9+
#include <bits/stdc++.h>
10+
using namespace std;
11+
12+
// Naive Approach
13+
// Time Complexity: O(n log n)
14+
// Space Complexity: O(1)
15+
int lastStoneWeightNaive(vector<int>& stones) {
16+
while (stones.size() > 1){
17+
sort(stones.begin(), stones.end());
18+
int largest = stones[stones.size()-1];
19+
int secondLargest = stones[stones.size()-2];
20+
stones.pop_back();
21+
if (largest == secondLargest){
22+
stones.pop_back();
23+
}
24+
else {
25+
stones[stones.size()-1] = largest-secondLargest;
26+
}
27+
}
28+
return stones.empty() ? 0 : stones[0];
29+
}
30+
31+
// Priority Queue
32+
// Time Complexity: O(n)
33+
// Space Complexity: O(n)
34+
int lastStoneWeightPQ(vector<int>& stones) {
35+
priority_queue<int> remainingStones(stones.begin(), stones.end());
36+
while (remainingStones.size() > 1){
37+
int largest = remainingStones.top(); remainingStones.pop();
38+
int secondLargest = remainingStones.top(); remainingStones.pop();
39+
remainingStones.push(largest - secondLargest);
40+
}
41+
return remainingStones.top();
42+
}

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
### Problems Solved
1818

19-
| Total | 42 |
19+
| Total | 43 |
2020
|:---:|:---:|
2121

2222
#### Search By Topic
@@ -36,7 +36,7 @@
3636
| Intervals | 1 |
3737
| Linked Lists | 5 |
3838
| Math & Geometry | 2 |
39-
| Priority Queue | 1 |
39+
| Priority Queue | 2 |
4040
| Sliding Window | 1 |
4141
| Stack | 2 |
4242
| Tries | 0 |
@@ -46,7 +46,7 @@
4646

4747
| Difficulty | Number |
4848
|:---|---:|
49-
| Easy | 41 |
49+
| Easy | 42 |
5050
| Medium | 1 |
5151
| Hard | 0 |
5252

0 commit comments

Comments
 (0)