Triangle problems
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Triangle problems ask for the best path from the top of a pyramid of numbers to the bottom, stepping to one of the two numbers below. Working from the bottom up lets each spot choose its better child. It is the pattern behind any branching structure where each choice splits into two.
Practical use cases
- Web app: Branching quiz game scoring. A quiz app has levels where each answer leads to one of two next questions worth different points. The team wants to show the maximum possible score a player could reach. Starting at the last level and writing the best score at each question works upward to the first question, which then shows the maximum. The editor can add a new question in the middle of the quiz and see the new maximum score at once, so level balancing becomes a quick daily task.
- Web app: Choose-your-own-adventure stories. An interactive story site has a branching storyline with a rating for each scene. The editor can see the best-rated path from the opening scene, found without tracing every possible route. With 20 layers the story has about a million possible paths, yet the editor sees the best one after about 200 additions, which makes review practical.
- System: Option pricing and Pascal-style tables. Finance tools price options by working backwards through a tree of up-or-down moves. Pascal's triangle itself is built the same layer-by-layer way. In each of these, the table is built from the bottom up, so every position already knows its best onward route before the top is even reached.
The story: The Pyramid of Diyas
For Diwali, Zoya and Aarav built a pyramid of diyas on the school lawn: one diya at the top, two on the next level, three on the next, and so on. Each diya had a price tag, the oil and wick it needed. They played a game: a tiny ant starts at the top and walks down. At each level it can step to either of the two diyas right below it (one to the left, one to the right). The ant pays the price of every diya it steps on. Which route is cheapest?
Aarav tried going top to bottom, always choosing the cheaper diya below. "Cheap now" ended him on a very costly diya later, a classic trap. Zoya said, "Let's start from the bottom. Standing on a bottom diya, the cost to go down is just that diya. One level up, each diya only has two choices below. Pick the cheaper one and add yourself."
Level by level she rewrote the pyramid from the bottom: every diya became its own price plus the cheaper of the two diyas under it. When she reached the single diya at the top, it already contained the cheapest trip for the whole pyramid. No extra notebook needed; she just updated the pyramid itself.
That is the triangle problem: DP on a triangle shape, where each cell has two children. Working from the bottom up avoids any dead ends and gives the answer at the top. The same pattern solves many "pyramid" puzzles.
How to spot this problem, and where you need it
You have a layered structure where each item leads to two items in the next layer, and you want the best or cheapest route from top to bottom without trying every path.
Signs you need it
- The data looks like a pyramid or levels, where each position connects to two positions in the next row.
- The number of full paths doubles at every level, so listing them is hopeless.
- Choosing the bigger child at each step from the top gives a worse total than a different route.
Where to use it in a project
- Computing best or maximum scores in branching quiz, game or story structures.
- Working backwards through layered decisions in a pricing or planning tool.
The solution
Start at the second-to-last row. For each number, add the better of the two numbers below it, and replace it with that total. Do the same for the row above, and keep moving up. When you reach the top, the single number there is the best total of the whole pyramid. You only use one array the size of the bottom row, updating it as you go.
Payoff: Before: checking about a million paths for 20 levels. After: about 200 small additions.
Explain it like I am 8
Stand at the top of a pyramid-shaped slide with a fork at every level. Instead of guessing a path from the top, let the pyramid tell you: from the bottom up, every spot writes down "the cheapest way to finish from me". When the information climbs to the top, the top already knows the best path.
How it works, step by step
- State:
dp[r][c]= the cheapest cost to finish from cell(r, c)down to the bottom (counting itself). - Base case: the bottom level:
dp = the cell's own value. - Transition:
dp[r][c] = tri[r][c] + min(dp[r+1][c], dp[r+1][c+1])(the two cells below). - Go bottom-up, from the second-last level to the top, so the cells below are ready.
- Answer: the single cell at the top. Keep just one row (the level below), or overwrite the triangle itself to save memory.
The code in four languages
PHP
<?php
// Cheapest top-to-bottom trip in a triangle. At each level step to one of two neighbours below.
// Work bottom-up so each cell can read the finished cells under it.
function cheapestTrip(array $tri): int {
$n = count($tri);
$dp = $tri[$n - 1]; // bottom level: cost is just the value itself
for ($r = $n - 2; $r >= 0; $r--) {
for ($c = 0; $c <= $r; $c++) {
// own cost + cheaper of the two cells below (below-left, below-right)
$dp[$c] = $tri[$r][$c] + min($dp[$c], $dp[$c + 1]);
}
}
return $dp[0]; // the top holds the answer
}
$pyramid = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]];
echo cheapestTrip($pyramid), "\n"; // 11 (2 + 3 + 5 + 1)JavaScript
// Cheapest top-to-bottom trip in a triangle. At each level step to one of two neighbours below.
// Work bottom-up so each cell can read the finished cells under it.
function cheapestTrip(tri) {
const n = tri.length;
const dp = tri[n - 1].slice(); // bottom level: cost is just the value itself
for (let r = n - 2; r >= 0; r--) {
for (let c = 0; c <= r; c++) {
// own cost + cheaper of the two cells below (below-left, below-right)
dp[c] = tri[r][c] + Math.min(dp[c], dp[c + 1]);
}
}
return dp[0]; // the top holds the answer
}
const pyramid = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]];
console.log(cheapestTrip(pyramid)); // 11 (2 + 3 + 5 + 1)Java
public class Main {
// Cheapest top-to-bottom trip in a triangle. At each level step to one of two neighbours below.
// Work bottom-up so each cell can read the finished cells under it.
static int cheapestTrip(int[][] tri) {
int n = tri.length;
int[] dp = tri[n - 1].clone(); // bottom level: cost is just the value itself
for (int r = n - 2; r >= 0; r--) {
for (int c = 0; c <= r; c++) {
// own cost + cheaper of the two cells below (below-left, below-right)
dp[c] = tri[r][c] + Math.min(dp[c], dp[c + 1]);
}
}
return dp[0]; // the top holds the answer
}
public static void main(String[] args) {
int[][] pyramid = {{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}};
System.out.println(cheapestTrip(pyramid)); // 11 (2 + 3 + 5 + 1)
}
}Go
package main
import (
"fmt"
"slices"
)
// Cheapest top-to-bottom trip in a triangle. At each level step to one of two neighbours below.
// Work bottom-up so each cell can read the finished cells under it.
func cheapestTrip(tri [][]int) int {
n := len(tri)
dp := slices.Clone(tri[n-1]) // bottom level: cost is just the value itself
for r := n - 2; r >= 0; r-- {
for c := 0; c <= r; c++ {
// own cost + cheaper of the two cells below (below-left, below-right)
dp[c] = tri[r][c] + min(dp[c], dp[c+1])
}
}
return dp[0] // the top holds the answer
}
func main() {
pyramid := [][]int{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}
fmt.Println(cheapestTrip(pyramid)) // 11 (2 + 3 + 5 + 1)
}Time: O(n²) · Extra space: O(n). A triangle with n levels has about n²/2 cells and each is visited once; one row of memory is enough.
Watch out for
- Greedy top-down ("always take the cheaper child"), which can walk into an expensive branch. Bottom-up avoids this.
- Overwriting a value before it has been read. Looping left to right is safe here, because
dp[c + 1]is still the old level when cell c reads it. - Off-by-one on the neighbours below. In a triangle, cell
(r, c)sits above(r+1, c)and(r+1, c+1).
Quick check
- Which two cells can the ant step to from cell (r, c)?
- (r+1, c) and (r+1, c+1)
- (r, c-1) and (r, c+1)
- (r-1, c) and (r+1, c)
- Why is bottom-up easier than top-down for this problem?
- It uses less code in every language
- Cells at the bottom have known answers (their own value) and can be built on, with no dead-end guessing
- Because triangles are heavy
- Triangle [[1],[2,3]]. What is the cheapest top-to-bottom total?
- 4
- 6
- 3