MediumNo. 0553

Optimal Division — LeetCode 553 Python Solution

Topics
Array, Math, Dynamic Programming
Reading time
2 min

The problem

You are given an integer array nums. The adjacent integers in nums will perform the float division.

Example

Input
nums = [1000,100,10,2]
Output
"1000/(100/10/2)"
Explanation
1000/(100/10/2) = 1000/((100/10)/2) = 200

Python solution

PythonSolution
class Solution:
    def optimalDivision(self, nums: List[int]) -> str:
        n = len(nums)
        if n == 1:
            return str(nums[0])
        if n == 2:
            return f'{nums[0]}/{nums[1]}'
        return f'{nums[0]}/({"/".join(map(str, nums[1:]))})'

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 553. Optimal Division is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0313Super Ugly NumberMedium
0368Largest Divisible SubsetMedium
0396Rotate FunctionMedium
0486Predict the WinnerMedium
0805Split Array With Same AverageHard
0877Stone GameMedium

Frequently asked questions

How hard is LeetCode 553. Optimal Division?

LeetCode 553. Optimal Division is rated Medium on LeetCode.

What topics does LeetCode 553. Optimal Division cover?

LeetCode 553. Optimal Division is tagged Array, Math and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.