Queries to evaluate the given equation in a range [ L , R ] | Function to obtain the middle index of the range ; Recursive function to get the sum of values in the given range from the array . The following are parameters for this function . st . Pointer to segment tree node . Index of current node in the segment tree ss & se . Starting and ending indexes of the segment represented by current node , i . e . , st [ node ] l & r . Starting and ending indexes of range query ; If the segment of this node lies completely within the given range ; Return maximum in the segment ; If the segment of this node lies outside the given range ; If segment of this node lies partially in the given range ; Function to return the maximum in the range from [ l , r ] ; Check for erroneous input values ; Function to conSegment Tree for the subarray [ ss . . se ] ; For a single element ; Otherwise ; Recur for left subtree ; Recur for right subtree ; Function to conSegment Tree from the given array ; Height of Segment Tree ; Maximum size of Segment Tree ; Allocate memory ; Fill the allocated memory ; Return the constructed Segment Tree ; Driver Code ; Build the Segment Tree from the given array
function getMid ( s , e ) { return ( s + Math . floor ( ( e - s ) / 2 ) ) ; } function MaxUtil ( st , ss , se , l , r , node ) { if ( l <= ss && r >= se ) return st [ node ] ; if ( se < l ss > r ) return - 1 ; let mid = getMid ( ss , se ) ; return Math . max ( MaxUtil ( st , ss , mid , l , r , 2 * node + 1 ) , MaxUtil ( st , mid + 1 , se , l , r , 2 * node + 2 ) ) ; } function getMax ( st , n , l , r ) { if ( l < 0 r > n - 1 l > r ) { document . write ( " " ) ; return - 1 ; } return MaxUtil ( st , 0 , n - 1 , l , r , 0 ) ; } function constructSTUtil ( arr , ss , se , st , si ) { if ( ss == se ) { st [ si ] = arr [ ss ] ; return arr [ ss ] ; } let mid = getMid ( ss , se ) ; st [ si ] = Math . max ( constructSTUtil ( arr , ss , mid , st , si * 2 + 1 ) , constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 ) ) ; return st [ si ] ; } function constructST ( arr , n ) { let x = ( Math . ceil ( Math . log ( n ) ) ) ; let max_size = 2 * Math . pow ( 2 , x ) - 1 ; let st = Array . from ( { length : max_size } , ( _ , i ) => 0 ) ; constructSTUtil ( arr , 0 , n - 1 , st , 0 ) ; return st ; } let arr = [ 5 , 2 , 3 , 0 ] ; let n = arr . length ; let st = constructST ( arr , n ) ; let Q = [ [ 1 , 3 ] , [ 0 , 2 ] ] ; for ( let i = 0 ; i < Q . length ; i ++ ) { let max = getMax ( st , n , Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) ; let ok = 0 ; for ( let j = 30 ; j >= 0 ; j -- ) { if ( ( max & ( 1 << j ) ) != 0 ) ok = 1 ; if ( ok <= 0 ) continue ; max |= ( 1 << j ) ; } document . write ( max + " " ) ; }