553.Optimal Division

来源:互联网 发布:引起妹子的兴趣知乎 编辑:程序博客网 时间:2024/06/16 14:11

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) = 200However, 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 = 501000/(100/(10/2)) = 501000/100/10/2 = 0.51000/100/(10/2) = 2
  • 题目描述:通过改变算数优先级,使最终数组运算结果最大。

  • 思路:考虑三种情况:

    1. 数组中只有一个数,直接返回
    2. 数组中有两个数,直接返回第一个数/第二个数
    3. 有三个及以上的数,把第二个数后面的和第一个数全部乘起来,最后除以第二个数。
  • 代码

    package String;/*** @Author OovEver* @Date 2017/12/10 22:42*/public class LeetCode553 {  public String optimalDivision(int[] nums) {      StringBuilder stringBuilder = new StringBuilder();      stringBuilder.append(nums[0]);      for(int i = 1;i<nums.length;i++) {          if (i == 1 && nums.length > 2) {              stringBuilder.append("/(").append(nums[i]);          } else {              stringBuilder.append("/").append(nums[i]);          }      }      return nums.length > 2 ? stringBuilder.append(")").toString() : stringBuilder.toString();  }}
原创粉丝点击