Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4.
However, you can add any number of parenthesis at any position to change the priority of operations. You should find out how to add parenthesis to get the maximum result, and return the corresponding expression in string format. Your expression should NOT contain redundant parenthesis.
Example:
Input: [1000,100,10,2]
Output: “1000/(100/10/2)”
Explanation:
1000/(100/10/2) = 1000/((100/10)/2) = 200
However, the bold parenthesis in “1000/((100/10)/2)” are redundant,
since they don’t influence the operation priority. So you should return “1000/(100/10/2)”.
Other cases:
1000/(100/10)/2 = 50
1000/(100/(10/2)) = 50
1000/100/10/2 = 0.5
1000/100/(10/2) = 2
Note:
The length of the input array is [1, 10].
Elements in the given array will be in range [2, 1000].
There is only one optimal division for each test case.
解法1:O(N^3)
这题的数学解法比较无聊,也不觉得对锻炼思路有帮助。倒是这个divide & conquer的解法很清楚明白。题目一拿到比较懵,如果细细思考可以想到。要得到最大值,需要dividend最大,divisor最小。那么就可以不停的尝试分割的位置,然后维护每一个子段的最大最小值以及产生最大最小值分割的括号摆放字符串。这里就需要用一个辅助class。
同时为了减少time complexity, 用一个二维数组做memorization来记录每一个子串的中间结果。
C++
Java