Maximum and Minimum Values of an Algebraic Expression | PHP 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
< ? php function minMaxValues ( $ arr , $ n , $ m ) { $ sum = 0 ; $ INF = 1000000000 ; $ MAX = 50 ; for ( $ i = 0 ; $ i < ( $ n + $ m ) ; $ i ++ ) { $ sum += $ arr [ $ i ] ; $ arr [ $ i ] += 50 ; } $ dp = array ( ) ; for ( $ i = 0 ; $ i < $ MAX + 1 ; $ i ++ ) { for ( $ j = 0 ; $ j < $ MAX * $ MAX + 1 ; $ j ++ ) $ dp [ $ i ] [ $ j ] = 0 ; } $ dp [ 0 ] [ 0 ] = 1 ; for ( $ i = 0 ; $ i < ( $ n + $ m ) ; $ i ++ ) { for ( $ k = min ( $ n , $ i + 1 ) ; $ k >= 1 ; $ k -- ) { for ( $ j = 0 ; $ j < $ MAX * $ MAX + 1 ; $ j ++ ) { if ( $ dp [ $ k - 1 ] [ $ j ] ) $ dp [ $ k ] [ $ j + $ arr [ $ i ] ] = 1 ; } } } $ max_value = -1 * $ INF ; $ min_value = $ INF ; for ( $ i = 0 ; $ i < $ MAX * $ MAX + 1 ; $ i ++ ) { if ( $ dp [ $ n ] [ $ i ] ) { $ temp = $ i - 50 * $ n ; $ max_value = max ( $ max_value , $ temp * ( $ sum - $ temp ) ) ; $ min_value = min ( $ min_value , $ temp * ( $ sum - $ temp ) ) ; } } echo ( " Maximum ▁ Value : ▁ " . $ max_value . " " . ▁ " Minimum Value : " . ▁ $ min _ value . ▁ " " } $ n = 2 ; $ m = 2 ; $ arr = [ 1 , 2 , 3 , 4 ] ; minMaxValues ( $ arr , $ n , $ m ) ; ? >