Python coding

Most points for clearing a row

A row holds the integers values. You remove its items one at a time, in any order, until the row is empty. Removing an item with value v scores left × v × right, where left and right are the values of its current neighbors: removed items are gone, so the row closes up, and a missing neighbor past either end counts as 1. Return the highest possible total score.

The row has 0 to 60 items, each from 0 to 100. Aim for O(n³) time.

Besides the tests, one large input (17 items) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • most_points([2,4,3]) → 33
  • most_points([6,1,2,9]) → 183
  • most_points([5]) → 5
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Choosing what to remove first leaves you stuck: the neighbors of everything else keep changing. Ask instead which item of a range is removed last.

Hint 2

Pad the row with a 1 at each end. Let best[lo][hi] be the most points for removing everything strictly between borders lo and hi, which stay in place.

Hint 3

If k goes last, its neighbors are lo and hi: best[lo][hi] = max(best[lo][k] + v[lo]·v[k]·v[hi] + best[k][hi]). Fill short ranges before long ones.

Solution and why it works
pythonO(n³) · O(n²)
def most_points(values: list[int]) -> int:
    vals = [1] + values + [1]            # the missing neighbors past the ends count as 1
    n = len(vals)
    best = [[0] * n for _ in range(n)]   # best[lo][hi]: most points for clearing strictly between lo and hi
    for width in range(2, n):            # short ranges first: longer ones are built from them
        for lo in range(n - width):
            hi = lo + width
            edge = vals[lo] * vals[hi]
            # k is removed last, when its only neighbors left are the borders lo and hi
            best[lo][hi] = max(best[lo][k] + edge * vals[k] + best[k][hi] for k in range(lo + 1, hi))
    return best[0][n - 1]

Fix the item removed last between two borders that stay put: its neighbors are then exactly those borders, and its left side is cleared independently of its right side. That splits a range into two smaller ranges, so ~n²/2 ranges × n choices of the last item give O(n³). Trying every removal order is n!, and caching by the remaining row still leaves 2ⁿ states. Greedy fails too: taking the biggest score each turn gets at most 135 on [6, 1, 2, 9], not 183.

Related lab: Big-O growth