All problems

Problem 200

Triangle Minimum Path

Medium · 20 pts · Array, Dynamic Programming

Problem

A triangle of numbers has N rows, and row i contains i numbers. Start at the top and move down one row at a time; from position j in a row, you may move to position j or j + 1 in the row below. Find the minimum possible sum of the numbers on a path from the top to the bottom row. Numbers can be negative. Work from the bottom up: the best sum from a position is its value plus the smaller of the best sums from its two neighbours below. After processing all rows, the top holds the answer.

Input

First line: integer N. Next N lines: row i has i integers.

Output

Print the minimum path sum.

Constraints

1 <= N <= 200; -10000 <= value <= 10000

Example input

4
2
3 4
6 5 7
4 1 8 3

Example output

11

Explanation

The path 2 → 3 → 5 → 1 moves to an adjacent number in each row and has sum 2 + 3 + 5 + 1 = 11. Every other path is larger, so the answer is 11.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Regular Expression Matching Next: Second Smallest Element