Online store~25 min2s · 256 MBtarget O(n³) time, O(n²) spaceclassic twin: lc-1039dp
A shop plans the lighting of a convex showroom floor. Corner i has a lamp with power rating ratings[i], and the corners are listed in order around the floor.
Cables join pairs of corners that are not neighbours, so that no two cables cross. They cut the floor into triangles. A triangle costs the product of the ratings of its three corners. Your team lead asks: "What is the least total cost of all the triangles?"
Write least_total_cost(ratings).
len(ratings) corners, at least 3, in order around a convex shape.Input: ratings = [2, 4, 5, 3, 6]
Output: 106Let cost[i][j] be the least cost of triangulating the part of the floor with corners i to j, whose base is the straight line from i to j. Two corners or fewer cost 0. For longer parts, some corner k between i and j forms the triangle on that base, so try every k and add the two smaller parts. We fill by number of corners.
| Corners | Part | Best k |
Cost |
|---|---|---|---|
| 3 | 0 to 2 | 1 | 40 |
| 3 | 1 to 3 | 2 | 60 |
| 3 | 2 to 4 | 3 | 90 |
| 4 | 0 to 3 | 2 | 70 |
| 4 | 1 to 4 | 3 | 132 |
| 5 | 0 to 4 | 3 | 106 |
For the whole floor, k = 1 costs 0 + 132 + 2 × 4 × 6 = 180. Then k = 2 costs 40 + 90 + 2 × 5 × 6 = 190. Last, k = 3 costs 70 + 0 + 2 × 3 × 6 = 106. The least is 106.
Input: ratings = [3, 4, 5]
Output: 60Three corners make one triangle: 3 × 4 × 5.
Input: ratings = [3, 7, 4, 5]
Output: 144Two ways to cut a square floor exist. One costs 3 × 7 × 4 + 3 × 4 × 5 = 144, and the other costs 3 × 7 × 5 + 7 × 4 × 5 = 245. The least is 144.
3 ≤ len(ratings) ≤ 2001 ≤ ratings[i] ≤ 100The number of ways to cut a floor into triangles grows like 4 to the power of n, so none can be listed. A table over parts has about n²/2 entries, and each tries up to n corners, so about n³/6 steps, which is 1,313,400 for n = 200. A cubic step count is affordable at this size.