forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1046-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
publicclassSolution
{
privatePriorityQueue<int,int>pq;
// T: O(NLogN)
publicintLastStoneWeight(int[]stones)
{
pq=newPriorityQueue<int,int>(newMaxHeapComparer());
AddStones(stones);
ComputeLastStoneWeight();
returnpq.Count==0?0:pq.Dequeue();
}
privatevoidAddStones(int[]stones)
{
foreach(varstoneinstones)
{
// 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)
privatevoidComputeLastStoneWeight()
{
while(pq.Count>1)
{
vary=pq.Dequeue();
varx=pq.Dequeue();
if(x!=y)
{
vardiff=y-x;
pq.Enqueue(diff,diff);
}
}
}
publicclassMaxHeapComparer:IComparer<int>
{
publicintCompare(intx,inty)
{
returny-x;
}
}
}