Problem

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.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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 do not 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

1
2
3
4
Input: nums = [2,3,4]
Output: "2/(3/4)"
Explanation: (2/(3/4)) = 8/3 = 2.667
It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667

Constraints

  • 1 <= nums.length <= 10
  • 2 <= nums[i] <= 1000
  • There is only one optimal division for the given input.

Solution

Method 1 – Greedy Parenthesis Placement

Intuition

To maximize the result, we want to divide the first number by the smallest possible denominator. This is achieved by dividing the first number by the result of dividing all the rest (i.e., group all numbers after the first in a single denominator). This avoids redundant parentheses.

Approach

  1. If the array has only one or two numbers, return the division as is (no parentheses needed).
  2. Otherwise, return the first number divided by the rest grouped in parentheses, joined by ‘/’.
  3. This ensures the denominator is minimized and the result is maximized.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
public:
    string optimalDivision(vector<int>& nums) {
        int n = nums.size();
        if (n == 1) return to_string(nums[0]);
        if (n == 2) return to_string(nums[0]) + "/" + to_string(nums[1]);
        string ans = to_string(nums[0]) + "/(";
        for (int i = 1; i < n; ++i) {
            if (i > 1) ans += "/";
            ans += to_string(nums[i]);
        }
        ans += ")";
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func optimalDivision(nums []int) string {
    n := len(nums)
    if n == 1 {
        return strconv.Itoa(nums[0])
    }
    if n == 2 {
        return fmt.Sprintf("%d/%d", nums[0], nums[1])
    }
    ans := fmt.Sprintf("%d/(%d", nums[0], nums[1])
    for i := 2; i < n; i++ {
        ans += fmt.Sprintf("/%d", nums[i])
    }
    ans += ")"
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    public String optimalDivision(int[] nums) {
        int n = nums.length;
        if (n == 1) return String.valueOf(nums[0]);
        if (n == 2) return nums[0] + "/" + nums[1];
        StringBuilder sb = new StringBuilder();
        sb.append(nums[0]).append("/(").append(nums[1]);
        for (int i = 2; i < n; i++) sb.append("/").append(nums[i]);
        sb.append(")");
        return sb.toString();
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    fun optimalDivision(nums: IntArray): String {
        val n = nums.size
        if (n == 1) return "${nums[0]}"
        if (n == 2) return "${nums[0]}/${nums[1]}"
        return buildString {
            append("${nums[0]}/(")
            append(nums[1])
            for (i in 2 until n) {
                append("/")
                append(nums[i])
            }
            append(")")
        }
    }
}
1
2
3
4
5
6
7
8
class Solution:
    def optimalDivision(self, nums: list[int]) -> str:
        n = len(nums)
        if n == 1:
            return str(nums[0])
        if n == 2:
            return f"{nums[0]}/{nums[1]}"
        return f"{nums[0]}/(" + "/".join(str(x) for x in nums[1:]) + ")"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
impl Solution {
    pub fn optimal_division(nums: Vec<i32>) -> String {
        let n = nums.len();
        if n == 1 {
            return nums[0].to_string();
        }
        if n == 2 {
            return format!("{}/{}", nums[0], nums[1]);
        }
        let mut ans = format!("{}/({}", nums[0], nums[1]);
        for i in 2..n {
            ans.push_str(&format!("/{}", nums[i]));
        }
        ans.push(')');
        ans
    }
}
1
2
3
4
5
6
7
8
class Solution {
    optimalDivision(nums: number[]): string {
        const n = nums.length
        if (n === 1) return `${nums[0]}`
        if (n === 2) return `${nums[0]}/${nums[1]}`
        return `${nums[0]}/(${nums.slice(1).join('/')})`
    }
}

Complexity

  • ⏰ Time complexity: O(n), where n is the length of nums. We build the string in one pass.
  • 🧺 Space complexity: O(n), for the output string.