AlgoTales · Roadmap

Maximum/minimum path

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

These problems ask for the best total along a path in a tree, such as the largest sum from top to bottom. Each node asks its children for their best, picks the better one, and adds its own value, building the answer from the bottom up.

Practical use cases

  • Web app: Cheapest route through a multi-step form. A booking flow has choices at each step, each with a cost, forming a tree of options. Asking each branch for its cheapest total, and picking the smaller, gives the cheapest complete path without trying every combination by hand. The shopper sees the cheapest total at once.
  • Web app: Best path in a game or quiz. A quiz game branches by answer and awards points on each branch. To show the maximum points a player could possibly earn, every question asks both branches for their best and adds its own points. The result screen shows the number at once.
  • System: Game decision trees. Game programs look ahead through a tree of moves, and each position takes the best score from its children, higher on your turn and lower on the opponent turn. Repeating that bottom-up step at every position is the whole trick behind how the program picks its move.

The story: Kabir and the Laddoo Trail

At Diwali, Mrs. Sharma set up a game in the school garden. A path started at the gate and split again and again, like a tree. At every junction there was a plate: some with laddoos, and some with a pinch of chilli powder (the plates were labelled with numbers, bigger meaning tastier).

"You walk from the gate to the end of any path," said Mrs. Sharma, "and your score is the sum of the plates you pass." Kabir wanted the maximum score. His little cousin, who hates sweets, wanted the minimum.

Kabir first tried to remember all paths in his head and promptly lost count. Mira whispered: "Don't. Stand at the end of the garden and work backwards. Every junction asks its two branches: 'what is your best total?' It takes the better answer and adds its own plate."

A leaf simply answers with its own number. Junction by junction the answers flowed up to the gate, and the gate's answer was the best total for the whole garden. The cousin used the same trick, taking the smaller answer at each junction.

How to spot this problem, and where you need it

You have a tree of choices with a value on each step, and you need the path with the highest or lowest total without listing every possible path.

Signs you need it

  • The problem says "maximum path sum", "minimum depth", "cheapest path from root to leaf" or "best score".
  • The structure branches at each step, and listing all paths would explode in number.
  • The answer for a node depends only on the best answers of its children plus its own value.

Where to use it in a project

  • Pricing, itinerary or workflow builders that pick the cheapest or best option sequence.
  • Game and quiz logic that evaluates the best outcome from a branching set of moves.

The solution

Write a function that returns the best total starting at one node. For a missing node it returns zero. Otherwise it asks the left and right child for their best, takes the larger for a maximum, or the smaller for a minimum, and adds its own value. Call it on the root. Each node is visited exactly once, so the cost grows in line with the number of nodes.

Payoff: Before: listing every path through a 1,000-node tree, an enormous number. After: one pass visiting each node once.

Explain it like I am 8

You are walking down a path of plates and adding up the numbers. At each fork you can only go left or right. To find the best total, every fork asks both paths how much they can give, picks the bigger answer, and adds its own plate. For the smallest total, pick the smaller answer instead.

How it works, step by step

  1. A path here runs from the root down to a leaf, adding every node's value on the way.
  2. Leaf: the best (and worst) total is simply its own value.
  3. Other node: max total = value + max(left best, right best). For the minimum, use min instead.
  4. If a node has only one child, take that child's answer. An empty side must never win, so treat it as -infinity for max and +infinity for min.
  5. The answer at the root is the maximum (or minimum) root-to-leaf path sum.

The code in four languages

PHP

<?php
class TreeNode {
    public ?TreeNode $left = null;
    public ?TreeNode $right = null;
    public function __construct(public int $val) {}
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree(): TreeNode {
    $root = new TreeNode(1);
    $root->left = new TreeNode(2);
    $root->right = new TreeNode(3);
    $root->left->left = new TreeNode(4);
    $root->left->right = new TreeNode(5);
    $root->right->right = new TreeNode(6);
    $root->left->right->left = new TreeNode(7);
    return $root;
}

// Best (max) and worst (min) root-to-leaf sums. An empty side must never win.
function maxPath(?TreeNode $n): int|float {
    if ($n === null) return -INF;
    if ($n->left === null && $n->right === null) return $n->val;   // leaf
    return $n->val + max(maxPath($n->left), maxPath($n->right));
}
function minPath(?TreeNode $n): int|float {
    if ($n === null) return INF;
    if ($n->left === null && $n->right === null) return $n->val;
    return $n->val + min(minPath($n->left), minPath($n->right));
}

// Bonus: collect every path so we can print them.
function allPaths(?TreeNode $n, array $prefix, array &$out): void {
    if ($n === null) return;
    $prefix[] = $n->val;
    if ($n->left === null && $n->right === null) { $out[] = $prefix; return; }
    allPaths($n->left, $prefix, $out);
    allPaths($n->right, $prefix, $out);
}

$root = sampleTree();
$paths = [];
allPaths($root, [], $paths);
foreach ($paths as $p) echo implode('-', $p) . ' = ' . array_sum($p) . PHP_EOL;
echo 'Max path sum: ' . maxPath($root) . PHP_EOL;   // 15
echo 'Min path sum: ' . minPath($root) . PHP_EOL;   // 7

JavaScript

class TreeNode {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree() {
  const root = new TreeNode(1);
  root.left = new TreeNode(2);
  root.right = new TreeNode(3);
  root.left.left = new TreeNode(4);
  root.left.right = new TreeNode(5);
  root.right.right = new TreeNode(6);
  root.left.right.left = new TreeNode(7);
  return root;
}

// Best (max) and worst (min) root-to-leaf sums. An empty side must never win.
function maxPath(n) {
  if (n === null) return -Infinity;
  if (n.left === null && n.right === null) return n.val;   // leaf
  return n.val + Math.max(maxPath(n.left), maxPath(n.right));
}
function minPath(n) {
  if (n === null) return Infinity;
  if (n.left === null && n.right === null) return n.val;
  return n.val + Math.min(minPath(n.left), minPath(n.right));
}

// Bonus: collect every path so we can print them.
function allPaths(n, prefix, out) {
  if (n === null) return;
  const path = prefix.concat([n.val]);
  if (n.left === null && n.right === null) { out.push(path); return; }
  allPaths(n.left, path, out);
  allPaths(n.right, path, out);
}

const root = sampleTree();
const paths = [];
allPaths(root, [], paths);
for (const p of paths) console.log(p.join('-') + ' = ' + p.reduce((a, b) => a + b, 0));
console.log('Max path sum: ' + maxPath(root));   // 15
console.log('Min path sum: ' + minPath(root));   // 7

Java

import java.util.*;
import java.util.stream.*;

public class Main {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    // The example tree:      1
    //                       /   \
    //                      2     3
    //                     / \     \
    //                    4   5     6
    //                       /
    //                      7
    static TreeNode sampleTree() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(6);
        root.left.right.left = new TreeNode(7);
        return root;
    }

    // Best (max) and worst (min) root-to-leaf sums. An empty side must never win.
    static int maxPath(TreeNode n) {
        if (n == null) return Integer.MIN_VALUE;
        if (n.left == null && n.right == null) return n.val;     // leaf
        return n.val + Math.max(maxPath(n.left), maxPath(n.right));
    }

    static int minPath(TreeNode n) {
        if (n == null) return Integer.MAX_VALUE;
        if (n.left == null && n.right == null) return n.val;
        return n.val + Math.min(minPath(n.left), minPath(n.right));
    }

    // Bonus: collect every path so we can print them.
    static void allPaths(TreeNode n, List<Integer> prefix, List<List<Integer>> out) {
        if (n == null) return;
        List<Integer> path = new ArrayList<>(prefix);
        path.add(n.val);
        if (n.left == null && n.right == null) { out.add(path); return; }
        allPaths(n.left, path, out);
        allPaths(n.right, path, out);
    }

    public static void main(String[] args) {
        TreeNode root = sampleTree();
        List<List<Integer>> paths = new ArrayList<>();
        allPaths(root, new ArrayList<>(), paths);
        for (List<Integer> p : paths) {
            int sum = p.stream().mapToInt(Integer::intValue).sum();
            System.out.println(p.stream().map(String::valueOf).collect(Collectors.joining("-")) + " = " + sum);
        }
        System.out.println("Max path sum: " + maxPath(root));   // 15
        System.out.println("Min path sum: " + minPath(root));   // 7
    }
}

Go

package main

import (
	"fmt"
	"math"
	"strconv"
	"strings"
)

type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// The example tree:      1
//
//	   /   \
//	  2     3
//	 / \     \
//	4   5     6
//	   /
//	  7
func sampleTree() *TreeNode {
	root := &TreeNode{Val: 1}
	root.Left = &TreeNode{Val: 2}
	root.Right = &TreeNode{Val: 3}
	root.Left.Left = &TreeNode{Val: 4}
	root.Left.Right = &TreeNode{Val: 5}
	root.Right.Right = &TreeNode{Val: 6}
	root.Left.Right.Left = &TreeNode{Val: 7}
	return root
}

// maxPath and minPath give the best and worst root-to-leaf sums. An empty side must never win.
func maxPath(n *TreeNode) int {
	if n == nil {
		return math.MinInt
	}
	if n.Left == nil && n.Right == nil {
		return n.Val // leaf
	}
	return n.Val + max(maxPath(n.Left), maxPath(n.Right))
}

func minPath(n *TreeNode) int {
	if n == nil {
		return math.MaxInt
	}
	if n.Left == nil && n.Right == nil {
		return n.Val
	}
	return n.Val + min(minPath(n.Left), minPath(n.Right))
}

// allPaths is a bonus: it collects every path so we can print them.
func allPaths(n *TreeNode, prefix []int, out *[][]int) {
	if n == nil {
		return
	}
	path := append(append([]int{}, prefix...), n.Val) // copy, so paths never share memory
	if n.Left == nil && n.Right == nil {
		*out = append(*out, path)
		return
	}
	allPaths(n.Left, path, out)
	allPaths(n.Right, path, out)
}

func main() {
	root := sampleTree()
	var paths [][]int
	allPaths(root, nil, &paths)
	for _, p := range paths {
		sum := 0
		parts := []string{}
		for _, v := range p {
			sum += v
			parts = append(parts, strconv.Itoa(v))
		}
		fmt.Println(strings.Join(parts, "-"), "=", sum)
	}
	fmt.Println("Max path sum:", maxPath(root)) // 15
	fmt.Println("Min path sum:", minPath(root)) // 7
}

Time: O(n) · Extra space: O(h). Each node is visited once; the recursion depth equals the tree height. Listing every path would need extra space for the paths themselves.

Watch out for

  • Letting an empty child win. For a node with one child, min(null-as-0, child) picks the empty side and gives a wrong answer. Use infinity for the missing side.
  • Stopping at any node instead of a leaf. A root-to-leaf path must end where there are no more children.
  • Mixing this up with "maximum path sum between any two nodes", a harder cousin where the path may bend and negative values matter.

Quick check

  1. What does a leaf return as its best (and worst) total?
    • The sum of its parent
    • Zero
    • Its own value
  2. In our example tree, which root-to-leaf path has the biggest sum?
    • 1-3-6
    • 1-2-5-7
    • 1-2-4
  3. Why must an empty child be treated as -infinity when finding the maximum?
    • So it never gets picked over a real child
    • Because it has a negative value
    • To make the code shorter