Minimize Expression Value with Parentheses (for mle also :)
Learn this problemProblem statement
You are given a string expr representing the sum of two positive integers. Neither integer contains a zero in its decimal representation.
Insert exactly one pair of parentheses so that the plus sign is inside the parentheses and there is at least one digit between the plus sign and each parenthesis.
Any digits outside the parentheses form multiplication factors. If there are no digits on one side of the parentheses, the missing factor is 1.
For example, 741+12 may become 74(1+1)2, which is evaluated as 74 * (1 + 1) * 2 = 296. Placements such as (74)1+12 and 741(+12) are invalid.
Return the smallest value obtainable from any valid placement of the parentheses.
A solution with time complexity no worse than O(expr.length^4) will fit within the execution time limit.
Function
minimizeExpressionValueWithParentheses(expr: String) → intExamples
Example 1
expr = "247+38"return = 170Placing the parentheses as 2(47+38) gives 2 * 85 = 170, the smallest value among all valid placements.
Example 2
expr = "12+34"return = 20The placement 1(2+3)4 evaluates to 1 * 5 * 4 = 20, which is minimal.
Example 3
expr = "999+999"return = 1998Putting both complete numbers inside the parentheses yields (999+999) = 1998. Every placement with an outside factor is larger.
Constraints
exprcontains exactly one plus sign.- At least one digit appears on each side of the plus sign.
- Every digit in
expris between1and9. - Every value produced by a valid placement fits in a signed
32-bit integer.