Optimal Division — LeetCode 553 Python Solution

MediumArrayMathDynamic Programming
Problem
#553
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

Python
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

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

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

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.

Get Stealth Interview