Skip to content

Commit 9415935

Browse files
committed
Runtime 63 ms (Top 78.86%) | Memory 102.0 MB (Top 30.8%)
1 parent 81d3ca7 commit 9415935

File tree

1 file changed

+29
-18
lines changed

1 file changed

+29
-18
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,35 @@
1-
// Runtime: 65 ms (Top 93.33%) | Memory: 101.6 MB (Top 93.33%)
21
class Solution {
32
public int[] maximumBeauty(int[][] items, int[] queries) {
4-
int n = queries.length, m = items.length;
5-
Arrays.sort(items, Comparator.comparingInt(o -> o[0]));
6-
int[] ans = new int[n];
7-
8-
for (int i = 0; i < m; i++)
9-
items[i][1] = Math.max(items[i][1], items[i > 0? i - 1 : 0][1]);
10-
11-
int j = 0;
12-
for (int q : queries){
13-
int lo = -1, hi = m - 1; //pad lo = -1 to mark no result
14-
while(lo < hi){
15-
int mid = lo + (hi - lo) / 2 + 1;
16-
if (q >= items[mid][0]) lo = mid;
17-
else hi = mid - 1;
18-
}
19-
ans[j++] = lo == -1? 0 : items[lo][1];
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];
2016
}
21-
2217
return ans;
2318
}
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+
}
2435
}

0 commit comments

Comments
 (0)