You are given an integer array nums. The adjacent integers in nums will perform the float division.
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.
Example 1:
Input: nums = [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 do not 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
Example 2:
Input: nums = [2,3,4] Output: "2/(3/4)" Explanation: (2/(3/4)) = 8/3 = 2.667 It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667
Constraints:
1 <= nums.length <= 102 <= nums[i] <= 1000The key observation is that to maximize the result of the division, we should minimize the denominator. We achieve this by grouping as many elements as possible in the denominator so that the result becomes maximum. Hence, we should divide the first number by all the numbers after the first number treated as one single division.
The solution starts by checking if the length of the array is 1 or 2. For these cases, the return is straightforward as no extra parentheses are needed. For more than two numbers, the first number is divided by the expression of the rest, enclosed in parentheses to ensure that division occurs from left to right within the parentheses, thus maximizing the result.
JavaScript
C
C++
Java
C#
Time Complexity: O(n), where n is the number of elements in nums. We iterate through the nums once to construct the string.
Space Complexity: O(n), for storing the joined string.
Noob Recursive Backtracker vs Dynamic Programming Tabulator • Greg Hogg • 1,290,185 views views
Watch 9 more video solutions →Practice Optimal Division with our built-in code editor and test cases.
Practice on FleetCode