Two ways, Python

  • 0

    Before I found out about the "trick":

    def optimalDivision(self, nums):
        return self.helper(nums)[1][1]
    def helper(self, nums):
        base = [nums[0], '/'.join([str(num) for num in nums])]
        for i in range(1, len(nums)):
            base[0] = base[0]/float(nums[i])
        lo, hi = base, base
        if len(nums) < 3:
            return [lo, hi]
        next_lo, next_hi = self.helper(nums[1:])
        if nums[0]/float(next_hi[0]) < lo[0]:
            lo = [nums[0]/float(next_hi[0]), str(nums[0])+'/'+'('+next_hi[1]+')']
        if nums[0]/float(next_lo[0]) > hi[0]:
            hi = [nums[0]/float(next_lo[0]), str(nums[0])+'/'+'('+next_lo[1]+')']
        return [lo, hi]


    def optimalDivision(self, nums):
        if len(nums) < 3:
            return '/'.join([str(num) for num in nums])
        return str(nums[0])+'/('+'/'.join([str(num) for num in nums[1:]])+')'

Log in to reply

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