Minimum and Maximum values of an expression with * and +

21 Jun, 2022
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
Java
Python3
C#
Javascript
// 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 notbool isOperator(char op){    return (op == '+' || op == '*');} // method prints minimum and maximum value// obtainable from an expressionvoid 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 methodsint main(){    string expression = "1+2*3+4*5";    printMinAndMaxValueOfExp(expression);    return 0;}
// Java program to get maximum and minimum// values of an expressionimport java.io.*;import java.util.*;class GFG{   // Utility method to check whether a character  // is operator or not  static boolean isOperator(char op)  {    return (op == '+' || op == '*');  }   // method prints minimum and maximum value  // obtainable from an expression  static void printMinAndMaxValueOfExp(String exp)  {    Vector<Integer> num = new Vector<Integer>();    Vector<Character> opr = new Vector<Character>();    String tmp = "";     //  store operator and numbers in different vectors    for (int i = 0; i < exp.length(); i++)    {      if (isOperator(exp.charAt(i)))      {        opr.add(exp.charAt(i));        num.add(Integer.parseInt(tmp));        tmp = "";      }      else      {        tmp += exp.charAt(i);      }    }     //  storing last number in vector    num.add(Integer.parseInt(tmp));     int len = num.size();    int[][] minVal = new int[len][len];    int[][] maxVal = new int[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] = Integer.MAX_VALUE;        maxVal[i][j] = 0;         //  initializing main diagonal by num values        if (i == j)          minVal[i][j] = maxVal[i][j]          = num.get(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.get(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.get(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    System.out.print(      "Minimum value : " + minVal[0][len - 1]      + ", Maximum value : " + maxVal[0][len - 1]);  }   //  Driver code to test above methods  public static void main(String[] args)  {    String expression = "1+2*3+4*5";    printMinAndMaxValueOfExp(expression);  }} // This code is contributed by Dharanendra L V.
# Python3 program to get maximum and minimum# values of an expression # Utility method to check whether a character# is operator or notdef isOperator(op):    return (op == '+' or op == '*') # method prints minimum and maximum value# obtainable from an expressiondef 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                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    print("Minimum value : ",minVal[0][llen - 1],", \            Maximum value : ",maxVal[0][llen - 1]) # Driver codeexpression = "1+2*3+4*5"printMinAndMaxValueOfExp(expression) # This code is contributed by mohit kumar 29
// C# program to get maximum and minimum// values of an expressionusing System;using System.Collections.Generic; public class GFG{   // Utility method to check whether a character  // is operator or not  static bool isOperator(char op)  {    return (op == '+' || op == '*');  }   // method prints minimum and maximum value  // obtainable from an expression  static void printMinAndMaxValueOfExp(string exp)  {    List<int> num = new List<int>();    List<char> opr = new List<char>();     string tmp = "";     //  store operator and numbers in different vectors    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];      }    }     //  storing last number in vector    num.Add(int.Parse(tmp));          int len = num.Count;    int[,] minVal = new int[len,len];    int[,] maxVal = new int[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] = Int32.MaxValue;        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    Console.Write("Minimum value : " +                  minVal[0, len - 1] +                  ", Maximum value : " +                  maxVal[0,len - 1]);   }   //  Driver code to test above methods  static public void Main ()  {    string expression = "1+2*3+4*5";    printMinAndMaxValueOfExp(expression);  }} // This code is contributed by avanitrachhadiya2155
<script> // JavaScript program to get maximum and minimum// values of an expression // Utility method to check whether a character// is operator or notfunction isOperator(op){    return (op == '+' || op == '*');}  // method prints minimum and maximum value  // obtainable from an expressionfunction printMinAndMaxValueOfExp(exp){    let num = [];    let opr = [];    let tmp = "";      //  store operator and numbers in different vectors    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];      }    }      //  storing last number in vector    num.push(parseInt(tmp));      let len = num.length;    let minVal = new Array(len);    let maxVal = new Array(len);      //  initializing minval and maxval 2D array    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;          //  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 (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 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    document.write(      "Minimum value : " + minVal[0][len - 1]      + ", Maximum value : " + maxVal[0][len - 1]);} //  Driver code to test above methodslet expression = "1+2*3+4*5";printMinAndMaxValueOfExp(expression); // This code is contributed by ab2127 </script>
Output:  
Minimum value : 27, Maximum value : 105
Time Complexity: O(n^3), as we have three nested loops in the function.
Space Complexity:  O(n^2), since we are using a 2D matrix to store the values of all the subproblems.
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
Rajat Singh 11
mohit kumar 29
dharanendralv23
avanitrachhadiya2155
ab2127
surinderdawra388
sanskar84
Microsoft
Dynamic Programming
Microsoft
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for possible path in 2D matrix
How to solve a Dynamic Programming Problem ?
Longest Common Subsequence | DP using Memoization
Floyd Warshall Algorithm | DP-16
Highway Billboard Problem
Count All Palindrome Sub-Strings in a String | Set 1
Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
Space and time efficient Binomial Coefficient
Bellman–Ford Algorithm | DP-23
Printing Items in 0/1 Knapsack