-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxBeautyCounter.java
53 lines (47 loc) · 1.46 KB
/
MaxBeautyCounter.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
package org.sean.array;
import java.util.Map;
import java.util.TreeMap;
/***
* 2070. Most Beautiful Item for Each Query
*/
public class MaxBeautyCounter {
public int[] maximumBeauty(int[][] items, int[] queries) {
// get rid of the duplicate ones, keep the entry with large value
TreeMap<Integer, Integer> map = new TreeMap<>(Integer::compare);
for (int[] p : items) {
if (map.containsKey(p[0])) {
if (map.get(p[0]) < p[1]) {
map.put(p[0], p[1]);
}
} else {
map.put(p[0], p[1]);
}
}
int size = map.size();
int[][] nItems = new int[size][2];
int index = 0;
for (int i : map.keySet()) {
nItems[index++] = new int[]{i, map.get(i)};
}
int maxSoFar = 0;
for (int[] pair : nItems) {
if (maxSoFar < pair[1]) {
maxSoFar = pair[1];
} else {
pair[1] = maxSoFar;
map.put(pair[0], pair[1]);
}
}
int[] result = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
int q = queries[i];
if (q < nItems[0][0]) {
result[i] = 0;
} else {
Map.Entry<Integer, Integer> entry = map.floorEntry(queries[i]);
result[i] = entry.getValue();
}
}
return result;
}
}