oneby7

2-D Dynamic Programming Paths in a grid

542. Triangle

Medium

You are given a triangle of integers, triangle. Row i, counting from 0, holds i + 1 numbers. So the top row holds one number, and each row holds one more than the row above it.

A path starts at the number in the top row and moves down one row at a time until it reaches the bottom row. From triangle[i][j] it moves to either triangle[i + 1][j] or triangle[i + 1][j + 1]. In the drawings, those are the number straight below and the number to the right of that one.

Return the smallest sum of the numbers on such a path.

Example 1

5378412963

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

Output: 16

Explanation: The cheapest path is 5 → 7 → 1 → 3, which adds up to 16. The path 5 → 3 → 4 → 6 starts with the smaller step but adds up to 18.

Example 2

-14-32-65

Input: triangle = [[-1], [4, -3], [2, -6, 5]]

Output: -10

Explanation: The path -1 → -3 → -6 adds up to -10.

Example 3

-7

Input: triangle = [[-7]]

Output: -7

Explanation: The triangle has one row, so the only path is the number -7 on its own.

Check your understanding

Work out the answer for this input before you write any code.

triangle = [[2], [1, 5], [9, 8, 1]]

Constraints

  • 1 ≤ triangle.length ≤ 450
  • triangle[i].length == i + 1
  • -104 ≤ triangle[i][j] ≤ 104

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.