-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLastStoneWeight.java
52 lines (43 loc) · 1.1 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
//my solution
public class LastStoneWeight {
int idx = 0;
public int lastStoneWeight(int[] stones) {
int len = stones.length;
int remainWeight = maxStone(stones);
while (len != 1) {
int max = maxStone(stones);
if (remainWeight < max) {
stones[this.idx] = remainWeight;
remainWeight = max;
continue;
}
remainWeight -= max;
len--;
}
return remainWeight;
}
public int maxStone(int[] stones) {
int max = 0;
for (int i = 0; i < stones.length; i++) {
if (stones[i] > max) {
max = stones[i];
this.idx = i;
}
}
stones[this.idx] = 0;
return max;
}
}
/*best solution
class Solution {
public int lastStoneWeight(int[] stones) {
int len = stones.length;
while (len >= 2) {
Arrays.sort(stones);
int diff = stones[len - 1] - stones[len - 2];
stones[--len - 1] = diff;
}
return stones[0];
}
}
*/