// Java code to implement above approach
import java.io.*;
import java.util.*;
class GFG {
static int[] segmentTree;
// Function to get mid
public static int getMid(int start,
int end)
{
return start + (end - start) / 2;
}
// Function to fill segment tree
public static void fillSegmentTree(int[][] arr)
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] o1,
int[] o2)
{
return o1[0] - o2[0];
}
});
int n = arr.length;
int maxHeight
= (int)Math.ceil(Math.log(n)
/ Math.log(2));
int maxSize
= 2 * (int)Math.pow(2, maxHeight) - 1;
segmentTree = new int[maxSize];
fillSegmentTreeUtil(segmentTree, arr,
0, n - 1, 0);
}
// Function to utilise the segment tree
public static int
fillSegmentTreeUtil(int[] segmentTree,
int[][] arr,
int start, int end,
int currNode)
{
if (start == end) {
segmentTree[currNode]
= arr[start][1];
return segmentTree[currNode];
}
int mid = getMid(start, end);
segmentTree[currNode] = Math.max(
fillSegmentTreeUtil(segmentTree,
arr, start,
mid, currNode
* 2
+ 1),
fillSegmentTreeUtil(segmentTree,
arr, mid + 1,
end, currNode
* 2
+ 2));
return segmentTree[currNode];
}
// Function to find the maximum rating
public static int findMaxRating(int[][] arr,
int[] query)
{
int n = arr.length;
return findMaxRatingUtil(segmentTree,
arr, 0, n - 1,
query[0],
query[1], 0);
}
// Function to utilise the
// maxRating function
public static int
findMaxRatingUtil(int[] segmentTree,
int[][] arr,
int start, int end,
int qStart,
int qEnd, int currNode)
{
if (qStart <= arr[start][0]
&& qEnd >= arr[end][0]) {
return segmentTree[currNode];
}
if (qStart > arr[end][0] || qEnd < arr[start][0]) {
return -1;
}
int mid = getMid(start, end);
return Math.max(
findMaxRatingUtil(segmentTree,
arr, start, mid,
qStart, qEnd,
currNode * 2 + 1),
findMaxRatingUtil(segmentTree,
arr, mid + 1,
end, qStart, qEnd,
currNode * 2 + 2));
}
// Driver code
public static void main(String[] args)
{
int[][] arr = { { 1000, 300 },
{ 1100, 400 },
{ 1300, 200 },
{ 1700, 500 },
{ 2000, 600 } };
fillSegmentTree(arr);
int[][] queries = { { 1000, 1400 },
{ 1700, 1900 },
{ 0, 3000 } };
for (int[] query : queries) {
System.out.println(
findMaxRating(arr, query));
}
}
}