MediumArrayMathDynamic Programming

Optimal Division

LeetCode
1 approach, code in all languages

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 <= 100
  • 1 <= nums[i] <= 1000
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now