Minimum and Maximum values of an expression with * and +
Last Updated :
27 Aug, 2024
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;
}
Java
// Java program to get maximum and minimum
// values of an expression
import 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
# 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
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 code
expression = "1+2*3+4*5"
printMinAndMaxValueOfExp(expression)
# This code is contributed by mohit kumar 29
C#
// C# program to get maximum and minimum
// values of an expression
using 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
JavaScript
<script>
// JavaScript program to get maximum and minimum
// values of an expression
// Utility method to check whether a character
// is operator or not
function isOperator(op)
{
return (op == '+' || op == '*');
}
// method prints minimum and maximum value
// obtainable from an expression
function 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 methods
let 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), as Two 2D arrays (minVal and maxVal) are created, each with dimensions n x n.
Similar Reads
Maximum and Minimum Values of an Algebraic Expression Given an algebraic expression of the form (x1 + x2 + x3 + . . . + xn) * (y1 + y2 + . . . + ym) and (n + m) integers. Find the maximum and minimum value of the expression using the given integers. Constraint : n <= 50 m <= 50 -50 <= x1, x2, .. xn <= 50 Examples : Input : n = 2, m = 2 arr[
14 min read
Sum and Product of minimum and maximum element of an Array Given an array. The task is to find the sum and product of the maximum and minimum elements of the given array. Examples: Input : arr[] = {12, 1234, 45, 67, 1} Output : Sum = 1235 Product = 1234 Input : arr[] = {5, 3, 6, 8, 4, 1, 2, 9} Output : Sum = 10 Product = 9 Take two variables min and max to
13 min read
Minimum and Maximum sum of absolute differences of pairs Given an array of N integers where N is even, find the minimum and maximum sum of absolute difference of N/2 pairs formed by pairing every element with one other element. Examples: Input: a[] = {10, -10, 20, -40} Output: min_sum = 40, max_sum = 80 Explanation: Pairs selected for minimum sum (-10, -4
8 min read
Find Maximum and Minimum of two numbers using Absolute function Given two numbers, the task is to print the maximum and minimum of the given numbers using Absolute function.Examples: Input: 99, 18 Output: Maximum = 99 Minimum = 18 Input: -10, 20 Output: Maximum = 20 Minimum = -10 Input: -1, -5 Output: Maximum = -1 Minimum = -5 Approach: This problem can be solve
5 min read
Maximize the expression (A AND X) * (B AND X) | Bit Manipulation Given two positive integers A and B such that A != B, the task is to find a positive integer X which maximizes the expression (A AND X) * (B AND X).Example: Input: A = 9 B = 8 Output: 8 (9 AND 8) * (8 AND 8) = 8 * 8 = 64 (maximum possible)Input: A = 11 and B = 13 Output: 9 Naive approach: One can ru
6 min read