
You are given ‘exp’ = 1*2+4*5+3, here the minimum and maximum value of the expression occurs when , (1*2) + (4*5) + 3 = 25, and 1*(2 + 4) *(5 + 3) = 48. Hence the answer is [25, 48].
The first line of input contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains a string ‘exp’ representing the expression given.
For each test case, print two space-separated integers representing the maximum and minimum value of equations respectively.
Print a separate line for each test case.
1 <= T <= 10
1 <= |exp| <= 100
Time Limit: 1 sec
You do not need to print anything. It has already been taken care of. Just implement the given function.
In this approach, we will recursively find the maximum and minimum value of every possible subexpression in the given expression.
To find the maximum/minimum value of the subexpression ‘exp[startIndex, endIndex]’, starting at the position, ‘startIndex’ and ending at ‘endIndex’, we can iterate over the subexpression and if we find an operator at position ‘i’, we can find add/multiply the subexpressions exp[startIndex, i - 1] and exp[i + 1, endIndex], we take the maximum/minimum of all the positions when we find an operand, in the subexpression.
We create two functions maxValue(startIndex, endIndex, exp) and minValue(startIndex, endIndex, exp), where startIndex and endIndex are starting and ending indices of the subexpression of ‘exp’.
The only difference between the functions is that in maxValue we are taking the maximum of all subexpressions, while in minValue we are taking the minimum of all expressions.
In this approach, we will do the same thing as the previous approach, but since it’s clearly observed that in the previous approach, some ranges are being calculated multiple times. To prevent this we will create a cache that will store solutions for every range So that we don’t have to recalculate it.
We will create the same two functions, maxValue(startIndex, endIndex, exp, cache) and minValue(startIndex, endIndex, exp, cache), where startIndex and endIndex are starting and ending indices of the subexpression of ‘exp’. Cache is the cache of solutions for each range.
In this approach, instead of just using a cache, we will use a smaller ranges solution to build larger ranges solutions. To find the value of the subexpression ‘exp[startIndex][endIndex]’, we will iterate from startIndex to endIndex, and whenever we find an operator in between, say at index ‘K’ we can find the value of the ‘exp[startIndex][k - 1]‘ and ‘exp[k + 1][endIndex]’.
We will separate operands and operators for simplicity.
To find the value of larger subexpressions we have to calculate the value of smaller length subexpressions first.