Mid Coding

Find the maximum sum path in a triangle (bottom-up DP)?

public int MaximumTotal(IList<IList<int>> triangle) {

int n = triangle.Count;

int[] dp = new int[n];

for (int i = 0; i < n; i++) dp[i] = triangle[n - 1][i];

for (int layer = n - 2; layer >= 0; layer--) {

for (int i = 0; i <= layer; i++) {

dp[i] = triangle[layer][i] + Math.Max(dp[i], dp[i + 1]);

return dp[0];

Explanation:

Start from bottom row, keep updating max path sums up to the top.

More from C# Programming Tutorial

All questions for this course