Zepruv › Coding problems

Optimal Division

Medium · Array, Math, Dynamic Programming

You are given an integer array nums. The adjacent integers in nums will perform the float division.
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)"

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)"

(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

Starter code (python)

class Solution(object):
    def optimalDivision(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        

Related problems

Previous: Student Attendance Record I · Next: Brick Wall · All problems

Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.