Queries to find the maximum array element after removing elements from a given range | Function to find the maximum element after removing elements in range [ l , r ] ; Store prefix maximum element ; Store suffix maximum element ; Prefix max till first index is first index itself ; Traverse the array to fill prefix max array ; Store maximum till index i ; Suffix max till last index is last index itself ; Traverse the array to fill suffix max array ; Store maximum till index i ; Traverse all queries ; Store the starting and the ending index of the query ; Edge Cases ; Otherwise ; Driver Code
function findMaximum ( arr , N , Q , queries ) { let prefix_max = [ ] ; let suffix_max = [ ] ; prefix_max [ 0 ] = arr [ 0 ] ; for ( let i = 1 ; i < N ; i ++ ) { prefix_max [ i ] = Math . max ( prefix_max [ i - 1 ] , arr [ i ] ) ; } suffix_max [ N - 1 ] = arr [ N - 1 ] ; for ( let i = N - 2 ; i >= 0 ; i -- ) { suffix_max [ i ] = Math . max ( suffix_max [ i + 1 ] , arr [ i ] ) ; } for ( let i = 0 ; i < Q ; i ++ ) { let l = queries [ i ] [ 0 ] ; let r = queries [ i ] [ 1 ] ; if ( l == 0 && r == ( N - 1 ) ) document . write ( " " ) ; else if ( l == 0 ) document . write ( suffix_max [ r + 1 ] + " " ) ; else if ( r == ( N - 1 ) ) document . write ( prefix_max [ l - 1 ] + " " ) ; else document . write ( Math . max ( prefix_max [ l - 1 ] , suffix_max [ r + 1 ] ) + " " ) ; } } let arr = [ 5 , 6 , 8 , 10 , 15 ] ; let N = arr . length ; let queries = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 1 , 4 ] ] ; let Q = queries . length ; findMaximum ( arr , N , Q , queries ) ;