forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1046-Last-Stone-Weight.cs
49 lines (41 loc) · 1.04 KB
/
1046-Last-Stone-Weight.cs
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
public class Solution
{
private PriorityQueue<int, int> pq;
// T: O(NLogN)
public int LastStoneWeight(int[] stones)
{
pq = new PriorityQueue<int, int>(new MaxHeapComparer());
AddStones(stones);
ComputeLastStoneWeight();
return pq.Count == 0 ? 0 : pq.Dequeue();
}
private void AddStones(int[] stones)
{
foreach (var stone in stones)
{
// T: Heapify is O(N) for every enqueued item
pq.Enqueue(stone, stone);
}
}
// T: O(NLogN), to get max value its O(LogN) and we perform this for N items => O(NLogN)
private void ComputeLastStoneWeight()
{
while (pq.Count > 1)
{
var y = pq.Dequeue();
var x = pq.Dequeue();
if (x != y)
{
var diff = y - x;
pq.Enqueue(diff, diff);
}
}
}
public class MaxHeapComparer : IComparer<int>
{
public int Compare(int x, int y)
{
return y - x;
}
}
}