Minimum and Maximum values of an expression with * and + | 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
function isOperator ( op ) { return ( op == ' ' op == ' ' ) ; } function printMinAndMaxValueOfExp ( exp ) { let num = [ ] ; let opr = [ ] ; let tmp = " " ; for ( let i = 0 ; i < exp . length ; i ++ ) { if ( isOperator ( exp [ i ] ) ) { opr . push ( exp [ i ] ) ; num . push ( parseInt ( tmp ) ) ; tmp = " " ; } else { tmp += exp [ i ] ; } } num . push ( parseInt ( tmp ) ) ; let len = num . length ; let minVal = new Array ( len ) ; let maxVal = new Array ( len ) ; for ( let i = 0 ; i < len ; i ++ ) { minVal [ i ] = new Array ( len ) ; maxVal [ i ] = new Array ( len ) ; for ( let j = 0 ; j < len ; j ++ ) { minVal [ i ] [ j ] = Number . MAX_VALUE ; maxVal [ i ] [ j ] = 0 ; if ( i == j ) minVal [ i ] [ j ] = maxVal [ i ] [ j ] = num [ i ] ; } } for ( let L = 2 ; L <= len ; L ++ ) { for ( let i = 0 ; i < len - L + 1 ; i ++ ) { let j = i + L - 1 ; for ( let k = i ; k < j ; k ++ ) { let 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 ; } } } document . write ( " " + minVal [ 0 ] [ len - 1 ] + " " + maxVal [ 0 ] [ len - 1 ] ) ; } let expression = " " ; printMinAndMaxValueOfExp ( expression ) ;