Leetcode-553

来源:互联网 发布:网络传销崩盘前兆 编辑:程序博客网 时间:2024/06/06 09:58

题目

题目链接

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
Note:

The length of the input array is [1, 10].
Elements in the given array will be in range [2, 1000].
There is only one optimal division for each test case.

分析

题目大意是给出一个整数数组(其实就是一个用除号连接的算式),现在可以在任意的位置插入小括号,这样就改变了数字原本的运算顺序,求解一种添加小括号的方法使整个算式计算的结果最大。
显然直接计算会有难度,分析如下:

原本的数组组成的算式可以表示为:a/b/c/d…
要使整个分式的结果最大,那么只需要让分子尽量大,分母尽量小就可以了,由于a一定会在分子,b一定会在分母上(无论括号加在什么地方),这样的算式总是可以表示为:
a*n1*n2…/b*m1*m2
如果有一种划分的方法,使分母只有一个b,那显然这就是整个式子的最大值了(注意这个地方是基于题目中给的每个数字的范围都是2-1000,也就是不会有小数,也就不存在“越乘越大”“越除越小”的情况了,所以说这个条件让题目变简单了),这样的话,我们就可以总在式子的这个地方添加括号:
a/(b/c/d…) = a/b*(c/d…)

java的代码如下:

public class Solution {  public String optimalDivision(int[] nums) {        String str1 = "";        if(nums.length==0)            return str1;        else if(nums.length == 1)            return str1+nums[0];        else if(nums.length ==2)            return str1 + nums[0] + "/" +nums[1];        else {            str1 += nums[0] + "/(";             for(int i=1;i<nums.length-1;i++)                 str1 += nums[i]+"/";             str1 += nums[nums.length-1]+")";             return str1;        }    }    public static void main(String[] args) {      Solution solution =new Solution();      int[] nums = {1};      System.out.print( solution.optimalDivision(nums));    }}