can be the last (or the outermost) one. Consider the case where the last one is “×” (that is, multiplication). In this case, we need to parenthesize two subexpressions
(5−8+7)and(4−8+9)
so that the product of their values is maximized. To find this out, we find
the minimum and maximum values of these two subexpressions:
From these values, we conclude that the maximum value of the product is 130.
Assume that the input dataset is of the form
d0op0d1op1⋯opn−1dn,
where each di is a digit and each opj∈{+,−,×} is an arithmetic operation. The discussion above suggests that we compute the minimum value and the maximum value of each subexpression of the form
El,r=dlopldl+1opl+1⋯opr−1dr,
where 0≤l≤r≤n. Let minValue(l,r) and maxValue(l,r) be, respectively, the minimum value and the maximum value of El,r. Then,
These two recurrence relations allow us to compute the optimal values for El,r by going through all possibilities of breaking El,r into two subexpressions El,m and Em+1,r.
Another way of looking at the resulting recurrence relation is the following. A natural way to visualize a particular parenthesizing is to represent it as a binary tree:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.