Minimum and Maximum values of an expression with * and +
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
class Solution {
public static void minMaxValues(String exp) {
// Converting String into array of Strings
ArrayList<StringBuilder> list = new ArrayList<>();
for (int i = 0; i < exp.length(); i++) {
StringBuilder str = new StringBuilder();
if (exp.charAt(i) == '+' || exp.charAt(i) == '*')
str.append(exp.charAt(i));
else {
while (i < exp.length() && exp.charAt(i) >= '0' && exp.charAt(i) <= '9')
str.append(exp.charAt(i++));
i--;
}
list.add(str);
}
String[] str = new String[list.size()];
for (int i = 0; i < list.size(); i++)
str[i] = list.get(i).toString();
int n = str.length;
// DP[i][j] -> Min/Max ans between [i,j]
int[][] minDP = new int[n][n], maxDP = new int[n][n];
// Diagonal base case
for (int i = 0; i < n; i += 2)
minDP[i][i] = maxDP[i][i] = Integer.parseInt(str[i]);
// Remember i,j stays at numerical values
for (int i = n - 1; i >= 0; i -= 2) {
for (int j = i + 2; j < n; j += 2) {
minDP[i][j] = Integer.MAX_VALUE;
maxDP[i][j] = Integer.MIN_VALUE;
// Consider all the symbols one be one for first execution
// K runs at symbol values
for (int k = i + 1; k <= j - 1; k += 2) {
int leftAnsMin = minDP[i][k - 1], rightAnsMin = minDP[k + 1][j];
int leftAnsMax = maxDP[i][k - 1], rightAnsMax = maxDP[k + 1][j];
int minAns, maxAns;
if (str[k].equals("+")) {
minAns = leftAnsMin + rightAnsMin;
maxAns = leftAnsMax + rightAnsMax;
} else {
minAns = leftAnsMin * rightAnsMin;
maxAns = leftAnsMax * rightAnsMax;
}
minDP[i][j] = Math.min(minDP[i][j], minAns);
maxDP[i][j] = Math.max(maxDP[i][j], maxAns);
}
}
}
System.out.println("Max Result : " + maxDP[0][n - 1]);
System.out.println("Min Result : " + minDP[0][n - 1]);
}
}
Last updated