Adding Parentheses 2
InterviewTime limit0.5sMemory limit512 MB
Place non-nested parentheses around single operators in a digit-operator expression to make its value as large as possible.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Math, Brute force
- Solved
- No attempts yet
Problem
There is an expression of length . The expression consists of integers between and inclusive and the operators +, -, and ×. Because multiplication has higher precedence than addition and subtraction, multiplication must be evaluated first. When evaluating an expression, it must be evaluated from left to right. For example, the result of is .
If parentheses are added to the expression, the subexpression inside the parentheses must be evaluated first. However, each pair of parentheses must contain exactly one operator. For example, if parentheses are added to as , the result is . Nested parentheses are not allowed. That is, and are not valid expressions because they contain parentheses inside parentheses.
Given an expression, write a program to find the maximum possible result of an expression that can be made by adding parentheses appropriately. There is no limit on the number of parentheses added, and none have to be added.
Input
The first line gives the length of the expression, . The second line gives the expression. Every integer in the expression is between and inclusive. The string starts with an integer, and operators and integers alternate. Each operator is one of +, -, *. Here * denotes the × operation, which is multiplication. Because only valid expressions are given, is odd.
Output
On the first line, print the maximum possible result of an expression obtained by adding parentheses appropriately. The answer is less than and greater than .