Given an expression which contains numbers and two operators ‘+’ and ‘*’, we need to find maximum and minimum value which can be obtained by evaluating this expression by different parenthesization.
Examples:
Input : expr = “1+2*3+4*5” Output : Minimum Value = 27, Maximum Value = 105 Explanation: Minimum evaluated value = 1 + (2*3) + (4*5) = 27 Maximum evaluated value = (1 + 2)*(3 + 4)*5 = 105
We can solve this problem by dynamic programming method, we can see that this problem is similar to matrix chain multiplication, here we are trying different parenthesization to maximize and minimize expression value instead of number of matrix multiplication.
In below code first we have separated the operators and numbers from given expression then two 2D arrays are taken for storing the intermediate result which are updated similar to matrix chain multiplication and different parenthesization are tried among the numbers but according to operators occurring in between them. At the end last cell of first row will store the final result in both the 2D arrays.
CPP
// C++ program to get maximum and minimum // values of an expression #include <bits/stdc++.h> using namespace std; // Utility method to check whether a character // is operator or not bool isOperator(char op) { return (op == '+' || op == '*'); } // method prints minimum and maximum value // obtainable from an expression void printMinAndMaxValueOfExp(string exp) { vector<int> num; vector<char> opr; string tmp = ""; // store operator and numbers in different vectors for (int i = 0; i < exp.length(); i++) { if (isOperator(exp[i])) { opr.push_back(exp[i]); num.push_back(atoi(tmp.c_str())); tmp = ""; } else { tmp += exp[i]; } } // storing last number in vector num.push_back(atoi(tmp.c_str())); int len = num.size(); int minVal[len][len]; int maxVal[len][len]; // initializing minval and maxval 2D array for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { minVal[i][j] = INT_MAX; maxVal[i][j] = 0; // initializing main diagonal by num values if (i == j) minVal[i][j] = maxVal[i][j] = num[i]; } } // looping similar to matrix chain multiplication // and updating both 2D arrays 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 current operator is '+', updating tmp // variable by addition if(opr[k] == '+') { minTmp = minVal[i][k] + minVal[k + 1][j]; maxTmp = maxVal[i][k] + maxVal[k + 1][j]; } // if current operator is '*', updating tmp // variable by multiplication else if(opr[k] == '*') { minTmp = minVal[i][k] * minVal[k + 1][j]; maxTmp = maxVal[i][k] * maxVal[k + 1][j]; } // updating array values by tmp variables if (minTmp < minVal[i][j]) minVal[i][j] = minTmp; if (maxTmp > maxVal[i][j]) maxVal[i][j] = maxTmp; } } } // last element of first row will store the result cout << "Minimum value : " << minVal[0][len - 1] << ", Maximum value : " << maxVal[0][len - 1]; } // Driver code to test above methods int main() { string expression = "1+2*3+4*5"; printMinAndMaxValueOfExp(expression); return 0; } |
Python3
# Python3 program to get maximum and minimum # values of an expression # Utility method to check whether a character # is operator or not def isOperator(op): return (op == '+' or op == '*') # method prints minimum and maximum value # obtainable from an expression def printMinAndMaxValueOfExp(exp): num = [] opr = [] tmp = "" # store operator and numbers in different vectors for i in range(len(exp)): if (isOperator(exp[i])): opr.append(exp[i]) num.append(int(tmp)) tmp = "" else: tmp += exp[i] # storing last number in vector num.append(int(tmp)) llen = len(num) minVal = [[ 0 for i in range(llen)] for i in range(llen)] maxVal = [[ 0 for i in range(llen)] for i in range(llen)] # initializing minval and maxval 2D array for i in range(llen): for j in range(llen): minVal[i][j] = 10**9 maxVal[i][j] = 0 # initializing main diagonal by num values if (i == j): minVal[i][j] = maxVal[i][j] = num[i] # looping similar to matrix chain multiplication # and updating both 2D arrays for L in range(2, llen + 1): for i in range(llen - L + 1): j = i + L - 1 for k in range(i, j): minTmp = 0 maxTmp = 0 # if current operator is '+', updating tmp # variable by addition if(opr[k] == '+'): minTmp = minVal[i][k] + minVal[k + 1][j] maxTmp = maxVal[i][k] + maxVal[k + 1][j] # if current operator is '*', updating tmp # variable by multiplication elif(opr[k] == '*'): minTmp = minVal[i][k] * minVal[k + 1][j] maxTmp = maxVal[i][k] * maxVal[k + 1][j] # updating array values by tmp variables if (minTmp < minVal[i][j]): minVal[i][j] = minTmp if (maxTmp > maxVal[i][j]): maxVal[i][j] = maxTmp # last element of first row will store the result print("Minimum value : ",minVal[0][llen - 1],", \ Maximum value : ",maxVal[0][llen - 1]) # Driver code expression = "1+2*3+4*5"printMinAndMaxValueOfExp(expression) # This code is contributed by mohit kumar 29 |
Output:
Minimum value : 27, Maximum value : 105
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Maximum and Minimum Values of an Algebraic Expression
- Minimum cells required to reach destination with jumps equal to cell values
- Minimum number of coins that can generate all the values in the given range
- Maximum sum subsequence with values differing by at least 2
- Maximum count of values of S modulo M lying in a range [L, R] after performing given operations on the array
- std::regex_match, std::regex_replace() | Regex (Regular Expression) In C++
- Evaluate a boolean expression represented as string
- Query to find the maximum and minimum weight between two nodes in the given tree using LCA.
- Split a given array into K subarrays minimizing the difference between their maximum and minimum
- Rearrange Odd and Even values in Alternate Fashion in Ascending Order
- Largest subsequence such that all indices and all values are multiples individually
- Maximize occurrences of values between L and R on sequential addition of Array elements with modulo H
- Flip minimum signs of array elements to get minimum sum of positive elements possible
- Minimum number greater than the maximum of array which cannot be formed using the numbers in the array
- Minimum cost to reach end of array array when a maximum jump of K index is allowed
- Count of arrays having consecutive element with different values
- Average of ASCII values of characters of a given string
- Probability of getting all possible values on throwing N dices
- Find the minimum element in a sorted and rotated array
- Minimum Cost Path with Left, Right, Bottom and Up moves allowed

