import java.util.*;
public class GFG {
public static class Node {
int minimum;
int maximum;
Node(int minimum, int maximum)
{
this.minimum = minimum;
this.maximum = maximum;
}
}
public static void main(String[] args)
{
int[] arr = { 1, 8, 5, 9, 6, 14, 2, 4, 3, 7 };
int n = arr.length;
Node[] st = constructST(arr, n);
int qs = 0;
int qe = 8;
Node result = MaxMin(st, n, qs, qe);
System.out.println("Minimum = " + result.minimum
+ " and Maximum = "
+ result.maximum);
}
public static int getMid(int s, int e)
{
return s + (e - s) / 2;
}
public static Node MaxMinUntill(Node[] st, int ss,
int se, int qs, int qe,
int index)
{
Node tmp;
Node left;
Node right;
if (qs <= ss && qe >= se)
return st[index];
if (se < qs || ss > qe) {
tmp = new Node(Integer.MAX_VALUE,
Integer.MIN_VALUE);
return tmp;
}
int mid = getMid(ss, se);
left = MaxMinUntill(st, ss, mid, qs, qe,
2 * index + 1);
right = MaxMinUntill(st, mid + 1, se, qs, qe,
2 * index + 2);
tmp = new Node(
Math.min(left.minimum, right.minimum),
Math.max(left.maximum, right.maximum));
return tmp;
}
public static Node MaxMin(Node[] st, int n, int qs,
int qe)
{
Node tmp;
if (qs < 0 || qe > n - 1 || qs > qe) {
System.out.println("Invalid Input");
tmp = new Node(Integer.MAX_VALUE,
Integer.MIN_VALUE);
return tmp;
}
return MaxMinUntill(st, 0, n - 1, qs, qe, 0);
}
public static void constructSTUtil(int[] arr, int ss,
int se, Node[] st,
int si)
{
if (ss == se) {
st[si] = new Node(arr[ss], arr[ss]);
return;
}
int mid = getMid(ss, se);
constructSTUtil(arr, ss, mid, st, si * 2 + 1);
constructSTUtil(arr, mid + 1, se, st, si * 2 + 2);
int min = Math.min(st[si * 2 + 1].minimum,
st[si * 2 + 2].minimum);
int max = Math.max(st[si * 2 + 1].maximum,
st[si * 2 + 2].maximum);
st[si] = new Node(min, max);
}
public static Node[] constructST(int[] arr, int n)
{
int x = (int)(Math.ceil(Math.log(n) / Math.log(2)));
int max_size = 2 * (int)(Math.pow(2, x)) - 1;
Node[] st = new Node[max_size];
constructSTUtil(arr, 0, n - 1, st, 0);
return st;
}
}