You are given a list of whole numbers, nums. Write them in order with a division sign between each pair, like 6/2/3/4. Read left to right, that divides 6 by 2, then by 3, then by 4.
You may add brackets anywhere to change which divisions happen first. Choose the brackets that make the value as large as possible and return that expression as a string. Leave out any bracket that does not change the result.
Example 1
Input: nums = [6, 2, 3, 4] Output: "6/(2/3/4)" Why: 2/3/4 = 1/6, and 6 divided by 1/6 is 36
2 more examples and the constraints
Example 2
Input: nums = [9, 3] Output: "9/3" Why: with two numbers no bracket changes anything
Example 3
Input: nums = [7] Output: "7" Why: a single number has no division at all
Constraints
- 1 ≤ length of nums ≤ 10
- 2 ≤ nums[i] ≤ 1,000
- Exactly one bracketing gives the largest value
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Interval DP over slicesO(n³)
- First over the restO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10 numbers | Verdict |
|---|---|---|---|
| Interval DP over slices | O(n³) | Works; heavy for what it does | |
| First over the rest | O(n) | Best; one line once you see it |
n = how many numbers are in the list.
Edge cases to test
- One number. [7] gives "7": no slash at all.
- Two numbers. [9, 3] gives "9/3": brackets around a single number are redundant.
- Three numbers. [5, 6, 7] gives "5/(6/7)", the smallest case that needs brackets.
- Ten numbers. The bracket opens after the first number and closes at the very end.
Common mistakes
- Writing "9/(3)" for two numbers: a bracket around one number is redundant.
- Nesting brackets, like "6/(2/(3/4))", which moves 4 back to the bottom.
- Trying to compare float values in the output instead of returning the expression text.
How to talk through it
- 1Clarify. Must I return the text or the value? What counts as a redundant bracket? Are all numbers at least 2?
- 2Give the DP. Any bracketing ends in one last division; keep the largest and smallest value per slice: O(n³).
- 3Find the shortcut. The first number is always on top, the second always below; everything else can go on top.
- 4Code the one-liner. Handle one and two numbers first, then first/(rest).
- 5Test out loud. Run one, two and three numbers before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?