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.
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.
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 firstname.lastname@example.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.
- Printing brackets in Matrix Chain Multiplication Problem
- Minimum sum subsequence such that at least one of every four consecutive elements is picked
- Number of palindromic paths in a matrix
- Sum of average of all subsets
- Count Distinct Subsequences
- Minimum insertions to form a palindrome | DP-28
- Subset Sum Problem | DP-25
- Word Wrap Problem | DP-19
- Palindrome Partitioning | DP-17
- Cutting a Rod | DP-13
- Egg Dropping Puzzle | DP-11
- 0-1 Knapsack Problem | DP-10
- Binomial Coefficient | DP-9
- Matrix Chain Multiplication | DP-8
- Coin Change | DP-7