LeetCode 553. Optimal Division

2021-07-23 11:31:01 浏览数 (2)

LeetCode 553. Optimal Division

问题描述

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.

Example: Input: [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

解题思路

  • 把数字看成两部分,第一个数为被除数
  • 要使商最大,则除数最小
  • 所以除数等于,第二个数除以剩下的所有数。

代码

代码语言:javascript复制
class Solution {
    public String optimalDivision(int[] nums) {
        if(nums.length == 1) {
            return String.valueOf(nums[0]);
        }
        
        if(nums.length == 2) {
            return String.valueOf(nums[0])   "/"   String.valueOf(nums[1]);
        }
        
        StringBuilder result = new StringBuilder();
        
        result.append(String.valueOf(nums[0]));
        result.append("/(");
        result.append(String.valueOf(nums[1]));
        
        
        for(int i = 2; i < nums.length; i  ) {
            result.append("/");
            result.append(String.valueOf(nums[i]));
        }
        result.append(")");
        
        return result.toString();
    }
}

0 人点赞