[LeetCode] Optimal Division

553. Optimal Division

You are given an integer array nums. The adjacent integers in nums will perform the float division.

  • For example, for nums = [2,3,4], we will evaluate the expression “2/3/4”.

However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.

Return the corresponding expression that has the maximum value in string format.

Note: your expression should not contain redundant parenthesis.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string optimalDivision(vector<int>& A) {
string res = to_string(A[0]);
if(A.size() == 1) return res;
if(A.size() == 2) return res + "/" + to_string(A[1]);
res += "/(";
for(int i = 1; i < A.size(); i++) {
res += to_string(A[i]);
res.push_back('/');
}
res.back() = ')';
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/27/PS/LeetCode/optimal-division/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.