Best Path Sum in Triangle with Required Cell Constraint
Dynamic ProgrammingAuto-graded · 22 test casesLast 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:
- Unrestricted maximum: The largest possible sum among all valid descending paths from apex to bottom.
- Constrained maximum: The largest possible sum among only those valid descending paths that pass through the cell at position
(r, c), meaning they includetriangle[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
nrows 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 <= 200len(triangle[i]) == i + 1for each rowi-10^4 <= triangle[i][j] <= 10^40 <= r <= n - 1and0 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires two separate dynamic programming computations that meet at the required cell.
Step 1: Top-Down Pass
Build a table best_from_top[i][j] representing the maximum sum achievable on any path starting from the apex and ending at cell (i, j).
-
Initialize:
best_from_top[0][0] = triangle[0][0] -
Recurrence: For each cell
(i, j), it can be reached from up to two parent cells in the previous row:- From
(i-1, j-1)ifj > 0 - From
(i-1, j)ifj < i
Take the maximum of the valid parents and add the current cell's value.
- From
The unrestricted maximum is simply the largest value in the bottom row: max(best_from_top[n-1]).
Step 2: Bottom-Up Pass
Build a table for best_to_bottom[i][j] representing the maximum sum achievable starting at cell (i, j) and descending to the final row.
-
Initialize:
best_to_bottom[n-1][j] = triangle[n-1][j] -
Recurrence: From cell
(i, j), you can move to(i+1, j)or(i+1, j+1):best_to_bottom[i][j] = triangle[i][j] + max(best_to_bottom[i+1][j], best_to_bottom[i+1][j+1])
We only need to compute this upward until we reach row r. A space-optimized implementation keeps just one row at a time.
Step 3: Combine at the Required Cell
Any path passing through cell (r, c) can be decomposed into:
- A prefix: apex to
(r, c) - A suffix:
(r, c)to bottom row
These segments are independent. The best constrained path combines the best prefix with the best suffix. Since both include triangle[r][c], we must subtract it once:
constrained_max = best_from_top[r][c] + best_to_bottom[r][c] - triangle[r][c]
Correctness
The approach relies on optimal substructure: the best path to any cell must use the best path to one of its parents. This property holds in both directions (top-down and bottom-up).
For the constrained case, since path choices before reaching (r, c) don't affect choices after, we can independently optimize each segment and combine them.
Negative values are handled correctly because we never artificially bound sums at zero or use empty paths—we always take the maximum over actual valid transitions.
Complexity
Time: O(n²) — We process each cell in the triangle exactly once in each pass. With n rows, there are approximately n²/2 cells total.
Space: O(n²) for storing the full best_from_top table. The best_to_bottom computation uses O(n) with a rolling array. This could be optimized to O(n) total by computing only the necessary row values.
Solution Code
from typing import List
def max_triangle_path_sums(triangle: List[List[int]], r: int, c: int) -> List[int]:
n = len(triangle)
# Build top-down DP: best_from_top[i][j] = max sum from apex to cell (i,j)
best_from_top = [triangle[0][:]]
for i in range(1, n):
prev_row = best_from_top[-1]
current_row = triangle[i]
new_row = [0] * (i + 1)
for j in range(i + 1):
candidate = None
# Can reach from parent at j (if exists)
if j < i:
candidate = prev_row[j]
# Can reach from parent at j-1 (if exists)
if j > 0 and (candidate is None or prev_row[j - 1] > candidate):
candidate = prev_row[j - 1]
new_row[j] = candidate + current_row[j]
best_from_top.append(new_row)
# Build bottom-up DP: best_to_bottom[j] = max sum from (i,j) to final row
best_to_bottom = triangle[n - 1][:]
for i in range(n - 2, r - 1, -1):
current_row = triangle[i]
best_to_bottom = [
current_row[j] + max(best_to_bottom[j], best_to_bottom[j + 1])
for j in range(i + 1)
]
unrestricted_max = max(best_from_top[n - 1])
constrained_max = best_from_top[r][c] + best_to_bottom[c] - triangle[r][c]
return [unrestricted_max, constrained_max]