Find the value of max ( f ( x ) ) | Javascript implementation of above approach ; Function to calculate the value ; forming the prefix sum arrays ; Taking the query ; finding the sum in the range l to r in array a ; finding the sum in the range l to r in array b ; Finding the max value of the function ; Finding the min value of the function ; Driver code
let MAX = 200006 ; let CONS = 32766 ; function calc ( a , b , lr , q , n ) { let M , m , i , j , k , l , r , suma , sumb , cc ; cc = 0 ; for ( i = 0 ; i < n - 1 ; ++ i ) { a [ i + 1 ] += a [ i ] ; b [ i + 1 ] += b [ i ] ; } while ( q != 0 ) { l = lr [ cc ++ ] ; r = lr [ cc ++ ] ; l -= 2 ; r -= 1 ; suma = a [ r ] ; sumb = b [ r ] ; if ( l >= 0 ) { suma -= a [ l ] ; sumb -= b [ l ] ; } M = Math . max ( CONS * suma + CONS * sumb , - CONS * suma - CONS * sumb ) ; M = Math . max ( M , Math . max ( CONS * suma - CONS * sumb , - CONS * suma + CONS * sumb ) ) ; m = Math . min ( CONS * suma + CONS * sumb , - CONS * suma - CONS * sumb ) ; m = Math . min ( m , Math . min ( CONS * suma - CONS * sumb , - CONS * suma + CONS * sumb ) ) ; document . write ( ( M - m ) + " " ) ; q -- ; } } let n = 5 , q = 2 ; let a = [ 0 , 7 , 3 , 4 , 5 ] ; let b = [ 0 , 3 , 1 , 2 , 3 ] ; let lr = new Array ( q * 2 ) ; lr [ 0 ] = 1 ; lr [ 1 ] = 1 ; lr [ 2 ] = 1 ; lr [ 3 ] = 3 ; calc ( a , b , lr , q , n ) ;