Maximum and Minimum Values of an Algebraic Expression | Javascript program to find the maximum and minimum values of an Algebraic expression of given form ; Finding sum of array elements ; shifting the integers by 50 so that they become positive ; dp [ i ] [ j ] represents true if sum j can be reachable by choosing i numbers ; if dp [ i ] [ j ] is true , that means it is possible to select i numbers from ( n + m ) numbers to sum upto j ; k can be at max n because the left expression has n numbers ; checking if a particular sum can be reachable by choosing n numbers ; getting the actual sum as we shifted the numbers by / 50 to avoid negative indexing in array ; Driver Code
var INF = 1000000000 var MAX = 50 function minMaxValues ( arr , n , m ) { var sum = 0 ; for ( var i = 0 ; i < ( n + m ) ; i ++ ) { sum += arr [ i ] ; arr [ i ] += 50 ; } var dp = Array . from ( Array ( MAX + 1 ) , ( ) => Array ( MAX * MAX + 1 ) . fill ( 0 ) ) ; dp [ 0 ] [ 0 ] = 1 ; for ( var i = 0 ; i < ( n + m ) ; i ++ ) { for ( var k = Math . min ( n , i + 1 ) ; k >= 1 ; k -- ) { for ( var j = 0 ; j < MAX * MAX + 1 ; j ++ ) { if ( dp [ k - 1 ] [ j ] ) dp [ k ] [ j + arr [ i ] ] = 1 ; } } } var max_value = - INF , min_value = INF ; for ( var i = 0 ; i < MAX * MAX + 1 ; i ++ ) { if ( dp [ n ] [ i ] ) { var temp = i - 50 * n ; max_value = Math . max ( max_value , temp * ( sum - temp ) ) ; min_value = Math . min ( min_value , temp * ( sum - temp ) ) ; } } document . write ( " " + max_value + " " + " " + min_value ) ; } var n = 2 , m = 2 ; var arr = [ 1 , 2 , 3 , 4 ] ; minMaxValues ( arr , n , m ) ;