Member-only story

Go solution to Minimum Score Triangulation of Polygon

Pierre-Marie Poitevin
2 min readMay 7, 2019

--

In this Leetcode problem, we are given a polygon, where each vertex (node) has a value. A triangle value is the multiplication of all its vertices values. We should divide it in triangles so that the sum of all the triangle values is minimal.

Problem statement

We can solve this problem in a divide and conquer greedy fashion, by noticing that by choosing the 3 minimal values and making a triangle out of them, we divide the polygon into 3 new polygons.

The approach is pretty straightforward, but coding details can be not as easy to manage because of border limits and array or index manipulation in the array. Here is my code for the solution:

func minScoreTriangulation(A []int) int {
if len(A) < 3 {
return 0
}
if len(A) == 3 {
return A[0] * A[1] * A[2]
}
var min [3]int
var ind [3]int
min[0] = 101
min[1] = 101
min[2] = 101
maxIndex := 0
for i, v := range A {
if v < min[maxIndex] {
min[maxIndex] = v
ind[maxIndex] = i
maxIndex = findMaxIndex(min)
}
}
a := findMinIndex(ind)
c := findMaxIndex(ind)
b := findMiddleIndex(a, c)

score := min[0] * min[1] * min[2] + minScoreTriangulation(A[ind[a]:ind[b]+1]) + minScoreTriangulation(A[ind[b]:ind[c]+1])
tmp := make([]int, 0)
tmp = append(tmp…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet