Optimal Division - 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 parentheses at any position to change the priority of operations. You want to add these parentheses such that 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 parentheses.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,4]
Output: "2/(3/4)"
💡 Note: We want to maximize 2/3/4. By adding parentheses as 2/(3/4), we get 2/0.75 = 2.67, which is maximum possible.
Example 2 — Two Elements
$ Input: nums = [2,3]
Output: "2/3"
💡 Note: With only two elements, no parentheses can be added. The result is simply 2/3.
Example 3 — Single Element
$ Input: nums = [5]
Output: "5"
💡 Note: With only one element, the expression is just the number itself: 5.

Constraints

  • 1 ≤ nums.length ≤ 10
  • 2 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Optimal Division INPUT Integer Array: nums 2 [0] 3 [1] 4 [2] Default expression: 2 / 3 / 4 Left to right evaluation: = 0.167 (small!) Goal: Maximize result using parentheses ALGORITHM STEPS 1 Observe Pattern a/b/c = a * (1/b) * (1/c) 2 Key Realization Maximize: keep nums[0] as numerator only 3 Minimize Denominator Divide rest among themselves: (b/c/d...) 4 Build Expression Format: a/(b/c/d...) Optimal Formula: nums[0] / (nums[1]/...) = nums[0] * nums[2] * ... FINAL RESULT Optimal Expression: "2/(3/4)" Evaluation: 3/4 = 0.75 2/0.75 = 2.667 Result: 2.667 Comparison: 2/3/4 = 0.167 2/(3/4) = 2.667 [OK] 16x improvement! Key Insight: To maximize a/b/c/d..., always keep the first element as the only numerator. Group all remaining elements in parentheses: a/(b/c/d...) This makes b/c/d... very small, resulting in a large final value. Time complexity: O(n) for string building. TutorialsPoint - Optimal Division | Optimal Solution (Greedy Approach)
Asked in
Google 12 Facebook 8
23.8K Views
Medium Frequency
~15 min Avg. Time
432 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen