KatInterview

Best Path Sum in Triangle with Required Cell Constraint

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingpathsoptimization

Last updated

Computes the maximum path sum descending through a triangular grid, both unconstrained and when forced through a specific cell.

You are given a triangular grid of integers. The grid contains n rows where row i (using 0-based indexing) contains exactly i + 1 elements. This means triangle[i][j] is valid when 0 <= j <= i.

A valid descending path begins at the apex (the single element in row 0) and progresses downward one row at a time until reaching the final row. When positioned at index j in row i, you may move to either index j or index j + 1 in the subsequent row i + 1. The path sum equals the total of all values encountered along the way.

Your task is to calculate two quantities:

  1. Unrestricted maximum: The largest possible sum among all valid descending paths from apex to bottom.
  2. Constrained maximum: The largest possible sum among only those valid descending paths that pass through the cell at position (r, c), meaning they include triangle[r][c].

Return both values as a two-element list: [unrestricted_max, constrained_max].

Important details:

  • Each path must visit exactly one cell per row, traversing all n rows from top to bottom.
  • Values in the triangle may be negative. Paths cannot terminate early or skip rows.
  • The cell (r, c) is guaranteed to lie on at least one valid path, so the constrained maximum always exists.

Constraints

  • 1 <= n <= 200
  • len(triangle[i]) == i + 1 for each row i
  • -10^4 <= triangle[i][j] <= 10^4
  • 0 <= r <= n - 1 and 0 <= c <= r

Examples

Example 1

Input: max_triangle_path_sums([[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]], 1, 0)

Output: [21, 18]

Example 2

Input: max_triangle_path_sums([[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]], 3, 0)

Output: [21, 15]

Example 3

Input: max_triangle_path_sums([[-5]], 0, 0)

Output: [-5, -5]

Hints

Hint 1

Consider computing the best path ending at each cell using dynamic programming from top to bottom.

Hint 2

To handle the constraint, think about splitting any path through (r,c) into two independent parts: before and after that cell.

Hint 3

Build a second DP table working upward from the bottom to find the best continuation from each cell to the final row.