-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLastStoneWeight.java
38 lines (32 loc) · 989 Bytes
/
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
package com.smlnskgmail.jaman.leetcodejava.easy;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Queue;
// https://leetcode.com/problems/last-stone-weight/
public class LastStoneWeight {
private final int[] input;
public LastStoneWeight(int[] input) {
this.input = input;
}
public int solution() {
Queue<Integer> weights = new PriorityQueue<>(
input.length,
Collections.reverseOrder()
);
for (int stone : input) {
weights.add(stone);
}
while (!weights.isEmpty()) {
int f = weights.peek() == null ? 0 : weights.poll();
int s = weights.peek() == null ? 0 : weights.poll();
if (f != s) {
int diff = Math.abs(f - s);
weights.add(diff);
if (weights.size() == 1) {
return diff;
}
}
}
return 0;
}
}