Problem · String

Minimize Expression Value with Parentheses (for mle also :)

Learn this problem
MediumByteDance logoByteDanceINTERNNEW GRADOA

Problem 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) → int

Examples

Example 1

expr = "247+38"return = 170

Placing the parentheses as 2(47+38) gives 2 * 85 = 170, the smallest value among all valid placements.

Example 2

expr = "12+34"return = 20

The placement 1(2+3)4 evaluates to 1 * 5 * 4 = 20, which is minimal.

Example 3

expr = "999+999"return = 1998

Putting both complete numbers inside the parentheses yields (999+999) = 1998. Every placement with an outside factor is larger.

Constraints

  • expr contains exactly one plus sign.
  • At least one digit appears on each side of the plus sign.
  • Every digit in expr is between 1 and 9.
  • Every value produced by a valid placement fits in a signed 32-bit integer.

More ByteDance problems

drafts saved locally
public int minimizeExpressionValueWithParentheses(String expr) {
    // write your code here
}
expr"247+38"
expected170
checking account