Most Beautiful Item for Each Query LeetCode solution in Java

1
class Solution {
2
public int[] maximumBeauty(int[][] items, int[] queries) {
3
int[] ans = new int[queries.length];
4
Arrays.sort(items, (a, b) -> (a[0] - b[0]));
5
int maxBeautySoFar = Integer.MIN_VALUE;
6
int[] maxBeauty = new int[items.length];
7

8
for (int i = 0; i < items.length; i++) {
9
if (maxBeautySoFar < items[i][1]) maxBeautySoFar = items[i][1];
10
maxBeauty[i] = maxBeautySoFar;
11
}
12

13
for (int i = 0; i < queries.length; i++) {
14
int idx = findLargestIdxWithPriceLessThan(items, queries[i]);
15
if (idx != Integer.MIN_VALUE) ans[i] = maxBeauty[idx];
16
}
17
return ans;
18
}
19

20
public int findLargestIdxWithPriceLessThan(int[][] items, int price) {
21
int l = 0;
22
int r = items.length - 1;
23
int maxIdxLessThanEqualToPrice = Integer.MIN_VALUE;
24
while (l <= r) {
25
int mid = (l + r) / 2;
26
if (items[mid][0] > price) {
27
r = mid - 1;
28
} else {
29
maxIdxLessThanEqualToPrice = Math.max(maxIdxLessThanEqualToPrice, mid);
30
l = mid + 1;
31
}
32
}
33
return maxIdxLessThanEqualToPrice;
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0