Minimum Score Triangulation of Polygon — LeetCode 1039 Python Solution

MediumArrayDynamic Programming
Problem
#1039
Reading time
2 min

The problem

You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex in clockwise order.

Python solution

Python
class Solution:
    def minScoreTriangulation(self, values: List[int]) -> int:
        @cache
        def dfs(i: int, j: int) -> int:
            if i + 1 == j:
                return 0
            return min(
                dfs(i, k) + dfs(k, j) + values[i] * values[k] * values[j]
                for k in range(i + 1, j)
            )

        return dfs(0, len(values) - 1)

Complexity

MeasureComplexity
TimeO(n^3)
SpaceO(n^2), where n is the number of vertices in the polygon auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1039. Minimum Score Triangulation of Polygon 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 1039. Minimum Score Triangulation of Polygon?
LeetCode 1039. Minimum Score Triangulation of Polygon is rated Medium on LeetCode.
What is the time complexity of LeetCode 1039. Minimum Score Triangulation of Polygon?
The Python solution on this page runs in O(n^3).
What is the space complexity of LeetCode 1039. Minimum Score Triangulation of Polygon?
The Python solution on this page uses O(n^2), where n is the number of vertices in the polygon auxiliary space.
What topics does LeetCode 1039. Minimum Score Triangulation of Polygon cover?
LeetCode 1039. Minimum Score Triangulation of Polygon is tagged Array 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