[刷题防痴呆] 0553 - 最优除法 (Optimal Div

2021-10-14  本文已影响0人  西出玉门东望长安

题目地址

https://leetcode.com/problems/optimal-division/

题目描述

553. Optimal Division

You are given an integer array nums. The adjacent integers in nums will perform the float division.

For example, for 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 don't 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)"
Example 3:

Input: nums = [2]
Output: "2"



思路

关键点

代码

class Solution {
    public String optimalDivision(int[] nums) {
        int n = nums.length;

        if (n == 1) {
            return nums[0] + "";
        }

        if (n == 2) {
            return nums[0] + "/" + nums[1];
        }
        StringBuffer sb = new StringBuffer();
        sb.append(nums[0]);
        sb.append("/(");
        sb.append(nums[1]);
        for (int i = 2; i < n; i++) {
            sb.append("/");
            sb.append(nums[i]);
        }
        sb.append(")");

        return sb.toString();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读