Pad the array with s: new_nums = [1] + nums + [1]. Now work with indices to .
function maxCoins(nums)
a := [1] + nums + [1]
m := length of a
dp := 2D array [m][m], all 0
for gap from 2 to m - 1
for i from 0 to m - gap - 1
j := i + gap
for k from i + 1 to j - 1
coins := a[i] * a[k] * a[j] + dp[i][k] + dp[k][j]
dp[i][j] := max(dp[i][j], coins)
return dp[0][m-1]
The answer is . Balloon is the last one burst in the interval , so and are still present as neighbors.
Time complexity: .
Space complexity: for the DP table.