Maximum and Minimum Values of an Algebraic Expression | C # 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
using System ; using System . Collections . Generic ; class GFG { static double INF = 1e9 ; static int MAX = 50 ; static void minMaxValues ( int [ ] arr , int n , int m ) { int sum = 0 ; for ( int i = 0 ; i < ( n + m ) ; i ++ ) { sum += arr [ i ] ; arr [ i ] += 50 ; } bool [ , ] dp = new bool [ MAX + 1 , MAX * MAX + 1 ] ; dp [ 0 , 0 ] = true ; for ( int i = 0 ; i < ( n + m ) ; i ++ ) { for ( int k = Math . Min ( n , i + 1 ) ; k >= 1 ; k -- ) { for ( int j = 0 ; j < MAX * MAX + 1 ; j ++ ) { if ( dp [ k - 1 , j ] ) dp [ k , j + arr [ i ] ] = true ; } } } double max_value = - 1 * INF , min_value = INF ; for ( int i = 0 ; i < MAX * MAX + 1 ; i ++ ) { if ( dp [ n , i ] ) { int temp = i - 50 * n ; max_value = Math . Max ( max_value , temp * ( sum - temp ) ) ; min_value = Math . Min ( min_value , temp * ( sum - temp ) ) ; } } Console . WriteLine ( " Maximum ▁ Value : ▁ " + max_value + " STRNEWLINE " + " Minimum ▁ Value : ▁ " + min_value + " STRNEWLINE " ) ; } public static void Main ( ) { int n = 2 , m = 2 ; int [ ] arr = { 1 , 2 , 3 , 4 } ; minMaxValues ( arr , n , m ) ; } }