//
//  main.cpp
//  Segment Tree
//
//  Created by Himanshu on 22/08/21.
//

#include <iostream>
#include <math.h>
#include <climits>
using namespace std;

const int N = 6;
int seg[2*N-1];

int construct (int arr[], int sb, int se, int si) {

  //Base case (only 1 element)
  if (sb == se) {
    seg[si] = arr[sb];
  } else {
    int mid = (sb+se)/2;  
    seg[si] = max((construct(arr, sb, mid, 2*si + 1)), 
                           (construct(arr, mid+1, se, 2*si + 2)));
  }

  return seg[si];
}

int getMax(int sb, int se, int x, int y, int i) {

 //Base case: Out of bound range
 if (sb > y || se < x) {
   return INT_MIN;
 } else if (sb >= x && se <= y) {
   return seg[i]; 
 } else {
   int mid = (sb+se)/2;
   return max((getMax(sb, mid, x, y, 2*i + 1)),  
              (getMax(mid+1, se, x, y, 2*i + 2)));
 }

}

int main() {
    int arr[] = {1, 3, 2, 7, 9, 11};
    
    // Constructing segment tree (preprocessing)
    construct(arr, 0, N-1, 0);

    // Print maximum value in arr[qs..qe]
    cout<<"Maximum element in the range:"<<endl;
    cout<<"x = 1, y = 5: "<<getMax(0, N-1, 1, 5, 0)<<endl;
    cout<<"x = 0, y = 3: "<<getMax(0, N-1, 0, 3, 0)<<endl;
    cout<<"x = 3, y = 5: "<<getMax(0, N-1, 3, 5, 0)<<endl;
    cout<<"x = 0, y = 4: "<<getMax(0, N-1, 0, 4, 0)<<endl;
    
    return 0;
}
