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:

1
2
3
4
5
6
7
8
9
10
11
12
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:

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

分析


题目中我们一个数组,让我们确定除法的顺序,从而得到值最大的运算顺序,默认情况下:$x/x1/x2/x3/…/xn = x/(x1x2x3…xn)$,无论怎么加括号,x1 一定是除数之一,x 一定是被除数之一,求原表达式的最大值,等于求除数的最小值,因此最佳方案为 $x/(x1/x2/x3…/xn)$

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public String optimalDivision(int[] nums) {
int denominatorCount = nums.length - 1;
String dividend = Integer.toString(nums[0]);
String denominator = "";
if (denominatorCount == 0) {
return dividend;
}
int i = 1;
for (; i < nums.length - 1; i++) {
denominator += Integer.toString(nums[i]);
denominator += "/";
}
denominator += Integer.toString(nums[i]);
if (denominatorCount > 1) {
denominator = "(" + denominator + ")";
}
return dividend + "/" + denominator;
}
}

题目来源