-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_881.java
60 lines (58 loc) · 2.32 KB
/
_881.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
package com.fishercoder.solutions.firstthousand;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public class _881 {
public static class Solution1 {
public int numRescueBoats(int[] people, int limit) {
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int w : people) {
map.put(w, map.getOrDefault(w, 0) + 1);
}
int boats = 0;
List<Integer> uniqWeights = new ArrayList(map.keySet());
int left = 0;
int right = uniqWeights.size() - 1;
while (left < right) {
int heavierWeight = uniqWeights.get(right);
int lighterWeight = uniqWeights.get(left);
if (heavierWeight + lighterWeight <= limit) {
int pairs = Math.min(map.get(heavierWeight), map.get(lighterWeight));
boats += pairs;
if (map.get(heavierWeight) == pairs && map.get(lighterWeight) == pairs) {
map.remove(heavierWeight);
map.remove(lighterWeight);
left++;
right--;
} else if (map.get(heavierWeight) == pairs) {
map.remove(heavierWeight);
map.put(lighterWeight, map.get(lighterWeight) - pairs);
right--;
} else {
map.remove(lighterWeight);
map.put(heavierWeight, map.get(heavierWeight) - pairs);
left++;
}
} else {
boats += map.get(heavierWeight);
map.remove(heavierWeight);
right--;
}
}
if (!map.isEmpty()) {
int weight = uniqWeights.get(left);
int remainingPeople = map.get(weight);
if (remainingPeople == 1) {
boats++;
} else {
if (weight * 2 <= limit) {
boats += (remainingPeople / 2 + ((remainingPeople % 2 == 0) ? 0 : 1));
} else {
boats += remainingPeople;
}
}
}
return boats;
}
}
}