text: Minimum and Maximum values of an expression with * and + | C # program to get maximum and minimum values of an expression ; Utility method to check whether a character is operator or not ; method prints minimum and maximum value obtainable from an expression ; store operator and numbers in different vectors ; storing last number in vector ; initializing minval and maxval 2D array ; initializing main diagonal by num values ; looping similar to matrix chain multiplication and updating both 2D arrays ; if current operator is ' + ' , updating tmp variable by addition ; if current operator is ' * ' , updating tmp variable by multiplication ; updating array values by tmp variables ; last element of first row will store the result ; Driver code to test above methods
code: using System ; using System . Collections . Generic ; public class GFG { static bool isOperator ( char op ) { return ( op == ' + ' op == ' * ' ) ; } static void printMinAndMaxValueOfExp ( string exp ) { List < int > num = new List < int > ( ) ; List < char > opr = new List < char > ( ) ; string tmp = " " ; for ( int i = 0 ; i < exp . Length ; i ++ ) { if ( isOperator ( exp [ i ] ) ) { opr . Add ( exp [ i ] ) ; num . Add ( int . Parse ( tmp ) ) ; tmp = " " ; } else { tmp += exp [ i ] ; } } num . Add ( int . Parse ( tmp ) ) ; int len = num . Count ; int [ , ] minVal = new int [ len , len ] ; int [ , ] maxVal = new int [ len , len ] ; for ( int i = 0 ; i < len ; i ++ ) { for ( int j = 0 ; j < len ; j ++ ) { minVal [ i , j ] = Int32 . MaxValue ; maxVal [ i , j ] = 0 ; if ( i == j ) { minVal [ i , j ] = maxVal [ i , j ] = num [ i ] ; } } } for ( int L = 2 ; L <= len ; L ++ ) { for ( int i = 0 ; i < len - L + 1 ; i ++ ) { int j = i + L - 1 ; for ( int k = i ; k < j ; k ++ ) { int minTmp = 0 , maxTmp = 0 ; if ( opr [ k ] == ' + ' ) { minTmp = minVal [ i , k ] + minVal [ k + 1 , j ] ; maxTmp = maxVal [ i , k ] + maxVal [ k + 1 , j ] ; } else if ( opr [ k ] == ' * ' ) { minTmp = minVal [ i , k ] * minVal [ k + 1 , j ] ; maxTmp = maxVal [ i , k ] * maxVal [ k + 1 , j ] ; } if ( minTmp < minVal [ i , j ] ) minVal [ i , j ] = minTmp ; if ( maxTmp > maxVal [ i , j ] ) maxVal [ i , j ] = maxTmp ; } } } Console . Write ( " Minimum ▁ value ▁ : ▁ " + minVal [ 0 , len - 1 ] + " , ▁ Maximum ▁ value ▁ : ▁ " + maxVal [ 0 , len - 1 ] ) ; } static public void Main ( ) { string expression = "1 + 2*3 + 4*5" ; printMinAndMaxValueOfExp ( expression ) ; } }