Optimal Division
1 approach, code in every language
Problem description
You are given a list of positive integers. Written left to right with division between each pair, the expression is evaluated as standard floating-point division and, without parentheses, associates from the left.
You may insert any valid set of parentheses to change the order of evaluation. Return the expression, as a string, that produces the maximum possible value. If several expressions tie, any correct maximal one is acceptable, and you should not add redundant parentheses.
Example 1
Input: nums = [1000,100,10,2]
Output: "1000/(100/10/2)"
Grouping as 1000/(100/10/2) evaluates to 1000/((100/10)/2) = 1000/5 = 200, which is the largest achievable value.
Example 2
Input: nums = [2,3,4]
Output: "2/(3/4)"
2/(3/4) equals 8/3, larger than the default left-to-right value 2/3/4 = 1/6.
Constraints
1 <= nums.length <= 1001 <= nums[i] <= 1000
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free