5 lines Tricky Python

  • 1

    This problem is a very tricky one. Basically the result is made of a product of some elements divided by the product of other elements. In the given example, we can see 1000/(100/10/2) == (1000*10*2)/(100).

    And one thing we shall notice is "NOTE 2. Elements in the given array will be in range [2, 1000]." What does it mean? It means every element can contribute to a bigger results as long as it's NOT in the denominator part! And we know no matter how we add parenthesis, the second element must be in the denominator if it exist. And that's it!

    class Solution(object):
        def optimalDivision(self, nums):
            :type nums: List[int]
            :rtype: str
            nums = list(map(str, nums))
            if len(nums) > 2:
                nums[1] = "(" + nums[1]
                nums[-1] = nums[-1] + ")"
            return "/".join(nums)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.