[LeetCode] Minimize Result by Adding Parentheses to Expression

2232. Minimize Result by Adding Parentheses to Expression

You are given a 0-indexed string expression of the form "<num1>+<num2>“ where <num1> and <num2> represent positive integers.

Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of ‘+’ and the right parenthesis must be added to the right of ‘+’.

Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them.

The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
string minimizeResult(string exp) {
auto p = exp.find('+');
string A = exp.substr(0,p), B = exp.substr(p+1);
string res = "("+exp+")";
long long val = stoll(A) + stoll(B);
for(int i = 0; i < A.length(); i++) {
for(int j = 1; j <= B.length(); j++) {
string amul = A.substr(0,i), aplus = A.substr(i);
string bplus = B.substr(0,j), bmul = B.substr(j);

long long now = (amul == "" ? 1 : stoll(amul)) * (stoll(aplus) + stoll(bplus)) * (bmul == "" ? 1 : stoll(bmul));
if(val > now) {
res = amul + "(" + aplus + "+" + bplus + ")" + bmul;
val = now;
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/02/PS/LeetCode/minimize-result-by-adding-parentheses-to-expression/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.