给定一个包含数字和两个运算符“+”和“*”的表达式,我们需要找到通过不同括号计算该表达式可以获得的最大值和最小值。
例子:
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
我们可以通过动态规划的方法解决这个问题,我们可以看到这个问题类似于矩阵链乘法,这里我们尝试不同的括号来最大化和最小化表达式值而不是矩阵乘法的次数。
在下面的代码中,我们首先将运算符和数字从给定的表达式中分离出来,然后采用两个二维数组来存储中间结果,这些结果类似于矩阵链乘法进行更新,并在数字之间尝试不同的括号,但根据它们之间出现的运算符。在第一行的最后一个单元格将最终结果存储在两个二维数组中。
CPP
// C++ program to get maximum and minimum
// values of an expression
#include
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 num;
vector 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 num = new Vector();
Vector opr = new Vector();
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
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
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 num = new List();
List opr = new List();
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
输出:
Minimum value : 27, Maximum value : 105
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。