LeetCode 553. Optimal Division 解题报告(python)

553. Optimal Division

  1. Optimal Division python solution

题目描述

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.
在这里插入图片描述

解析

x1 / x2 / x3 / … / xn
我们如何加括号使得其值最大
无论如何加括号,数列的第一个数只可能做分子,数列的第二个数只可能做分母。那么问题就变得简化了,我们只要让第三个到最后一个数变成分子就好了,那么一定是最大的!

例子
1000/(100/10/2) == (1000102)/(100)

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)
        

Reference

https://leetcode.com/problems/optimal-division/discuss/101721/5-lines-Tricky-Python

发布了131 篇原创文章 · 获赞 6 · 访问量 6919

猜你喜欢

转载自blog.csdn.net/Orientliu96/article/details/104304944