Minimize Expression Value with Parentheses
Learn this problemProblem statement
You are given a string expr representing the sum of two positive decimal integers. Neither integer contains the digit 0.
Insert exactly one pair of parentheses so that the plus sign is inside the parentheses and at least one digit lies between each parenthesis and the plus sign.
Digits before the left parenthesis form a left multiplication factor, and digits after the right parenthesis form a right multiplication factor. If either factor is absent, use 1. The digits inside the parentheses form the two addends.
For example, 741+12 may become 74(1+1)2, which has value 74 * (1 + 1) * 2 = 296.
Return the minimum numeric value over all valid placements of the parentheses.
Function
minimizeExpressionValueWithParentheses(expr: String) → intExamples
Example 1
expr = "741+12"return = 296The placement 74(1+1)2 evaluates to 74 * 2 * 2 = 296. Every other valid placement has a value of at least 296.
Example 2
expr = "247+38"return = 170Placing the parentheses as 2(47+38) gives 2 * 85 = 170, which is minimal.
Example 3
expr = "999+999"return = 1998Enclosing both complete numbers gives (999+999) = 1998. Leaving any digit outside introduces a factor that makes the value larger.
Constraints
3 <= expr.length <= 10.exprcontains exactly one plus sign.- At least one digit appears on each side of the plus sign.
- Every digit in
expris between1and9.