715. Triangle Descent

Medium3.5 points estimatedArrayDynamic Programming3 hints

A marble rolls down a pyramid of pegs given as an n x n array triangle. Row i of the pyramid consists of the first i + 1 entries of triangle[i]; every entry after those is padding and must be ignored, whatever it contains.

The marble starts on the single peg of row 0. From the peg at column j of row i it may drop to column j or column j + 1 of row i + 1. Return the smallest possible sum of the pegs touched on a trip from the top row to the bottom row (row n - 1).

Aim for time O(n^2) and extra space O(n).

Example 1

Input:
triangle = [[3,99,99,99],[7,2,99,99],[1,6,4,99],[8,2,9,5]]
Output:
13
Explanation:

The trip 3, 2, 6, 2 sums to 13, the lightest, and the 99 padding is never read.

Example 2

Input:
triangle = [[-4,0,0],[2,-6,0],[5,1,3]]
Output:
-9
Explanation:

Going -4, -6, 1 gives -9, and no other trip is lighter.

Constraints

1 ≤ n ≤ 300

-100 ≤ triangle[i][j] ≤ 100 for j ≤ i; padding entries may be any integer in the same range

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n^2)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…