How to maximize and minimize mathematical expression using recursion?

The expression consists of numbers (0-9), separated by one of two operators: *'and' +'. There are no spaces between characters.

Example: 1+2*3+4*5

We need to find out the maximum and minimum value that we can get using the brackets in the appropriate places.

Maximum value: 105 = (1+2)*(3+4)*5

Minimum value: 27 = 1+2*3+4*5

Am I looking for a recursive way to do this? Any ideas would be appreciated.

+4
source share
1 answer

Minimization :

: , , , , . minimize(expr). ? , . , minimize . .

:

int minimize(string expr)
    if isNumber(expr) then // If it is one number, return it.
        return value(expr)
    int res = infinity
    for int i <- 0 .. lenght expr - 1
        if expr[i] == '+' then
            res = min(res, minimize(expr[0 .. i - 1]) +
                           minimize(expr[i + 1 .. length expr - 1])
        if expr[i] == '*' then
            res = min(res, minimize(expr[0 .. i - 1]) * 
                           minimize(expr[i + 1 .. length expr - 1])
    return res

:

, .

? , () , () .

memoization, ( ) .

+3

All Articles