Skip to main content

Leetcode 1046

· One min read
Junhe Chen

Very straightforward question, just mimc the instruction using priority queue.

class Solution {
public int lastStoneWeight(int[] stones) {
// very straight forward, we use priority queue to ensure we polling the largest 2 stones
PriorityQueue<Integer> pq = new PriorityQueue<>((a,b)->{return b - a;});
for(int stone : stones){
pq.add(stone);
}
// while we have 2 or more stones
while(pq.size() > 1){
int a = pq.poll();
int b = pq.poll();
if(a != b){
int remain = Math.abs(a - b);
pq.add(remain);
}
}
// return nothing if we got no stone or last stone standing.
return pq.isEmpty() ? 0 : pq.poll();
}
}