-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathLastStoneWeight.java
67 lines (59 loc) · 1.82 KB
/
LastStoneWeight.java
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// @saorav21994
// TC : O(nlogn)
// SC : O(n)
// Tried using BFS on normal queue, but failed. So took priority queue.
class Solution {
public int lastStoneWeight(int[] stones) {
Arrays.sort(stones);
PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
for (int i = stones.length-1; i >= 0; i--) {
queue.offer(stones[i]);
}
while (queue.size() > 1) {
// System.out.println("queue size beg = "+ queue.size());
int size = queue.size();
while (size-- > 0) {
// System.out.println("queue size inner while = "+ size);
int top1 = queue.poll();
// System.out.println("top1 = "+ top1);
int top2 = 0;
if (size > 0) {
top2 = queue.poll();
size -= 1;
}
// System.out.println("top2 = "+ top2);
if (top2 != 0) {
if (top1 != top2) {
queue.offer(Math.abs(top1-top2));
}
}
else {
queue.offer(top1);
}
}
}
if (queue.size() == 1)
return queue.poll();
return 0;
}
}
// Author: Shobhit Behl (LC: shobhitbruh)
class Solution {
public int lastStoneWeight(int[] a) {
PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());
for(int v:a){
pq.add(v);
}
while(pq.size()>1){
int x=pq.remove();
int y=pq.remove();
if(Math.abs(x-y)>0){
pq.add(Math.abs(x-y));
}
}
if(pq.size()==0){
return 0;
}
return pq.remove();
}
}