We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Optimal Division

Number: 553

Difficulty: Medium

Paid? No

Companies: Amazon


Problem Description

Given an integer array nums, the task is to add parentheses into the expression nums[0] / nums[1] / ... / nums[n-1] such that its evaluated result is maximized. The catch is that you must output the expression as a string without any redundant parentheses.


Key Insights

  • If the array contains only one number, simply return that number as a string.
  • If the array contains two numbers, the optimal expression is just "a/b" with no parentheses needed.
  • For arrays with more than two elements, placing parentheses around the denominator (all numbers except the first) minimizes the division result in the denominator, thereby maximizing the overall value.
  • The general optimal expression for n>=3 is: first_number / (second_number / third_number / ... / last_number).
  • Ensure that the expression contains no redundant parentheses as per the problem constraint.

Space and Time Complexity

Time Complexity: O(n) – We iterate through the list to construct the result expression. Space Complexity: O(n) – The space used to build the resulting string is proportional to the length of the input array.


Solution

The solution leverages a greedy observation: to maximize the result of a series of divisions, we need to minimize the denominator. For an expression like a/b/c/d, placing parentheses as a/(b/c/d) minimizes the overall denominator.

For arrays with a length of 1 or 2, the answer is trivial:

  • Length 1: Return the number as a string.
  • Length 2: Return "a/b" without extra parentheses.

For arrays of length 3 or more, by grouping all elements after the first inside one pair of parentheses, i.e. "a/(b/c/d/...)", we guarantee the maximum evaluation.

The approach:

  1. Check if the array length is 1 or 2 and handle these cases directly.
  2. Otherwise, for n>=3, construct the expression by concatenating the first number, followed by "/(", then all remaining numbers separated by "/", and finally a closing ")".

Code Solutions

def optimalDivision(nums):
    # If there's only one number, return it directly.
    if len(nums) == 1:
        return str(nums[0])
    # If there are exactly two numbers, no need for parentheses.
    if len(nums) == 2:
        return str(nums[0]) + "/" + str(nums[1])
    # For more than two numbers, add parentheses around the denominator.
    # Join all numbers from the second element with '/'.
    return str(nums[0]) + "/(" + "/".join(str(num) for num in nums[1:]) + ")"

# Example test case:
print(optimalDivision([1000,100,10,2]))  # Expected output: "1000/(100/10/2)"
← Back to All Questions