2232. Minimize Result by Adding Parentheses to Expression

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 2232

class Solution:
    def minimizeResult(self, expression: str) -> str:
        l, r = expression.split("+")
        m, n = len(l), len(r)
        mi = inf
        res = None
        for i in range(m):
            for j in range(n):
                c = int(l[i:]) + int(r[: j + 1])
                a = 1 if i == 0 else int(l[:i])
                b = 1 if j == n - 1 else int(r[j + 1 :])
                if (t := a * b * c) < mi:
                    mi = t
                    res = f"{l[:i]}({l[i:]}+{r[: j + 1]}){r[j + 1:]}"
        return res