cswork / templatesOpen the Line 500 list

STOP 31 · DYNAMIC PROGRAMMING

Path, Tree, and Game States

Tree DP: each node returns (take, skip) O(n)

Contest ratings Rating 1954–Rating 2035· median Rating 1995(2 of 6 problems rated by zerotrac)

Open the Line 500 list · stop 31 · 6 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 2 companies · in 2 reportsTikTok / ByteDance 1, Waymo 1

Warm up with this one

LC 403Frog JumpHard
Stuck? Peek at the approach

Recognize that reaching the same stone with different jump lengths changes future reachability and requires another state dimension.

Key points

  1. Tree DP runs post-order: get both children's results first, then compute the current node, returning a small tuple.
  2. Splitting the state by whether the current node is taken is simpler than looking two levels down from the parent, and nothing is computed twice.
  3. Two-player games often use the score difference for the player to move: dp[i][j] = max(nums[i] - dp[i+1][j], nums[j] - dp[i][j-1]).

Common pitfalls

  • The grandparent-plus-grandchildren version without memoization repeats work exponentially.
  • When the node is skipped the children are free, so take max(take, skip) for each child, not just take.
  • Modelling a game by "my score" usually forces you to track the opponent as well; the difference is simpler.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Tree traversal · stack and queue

Walk the tree in preorder, inorder, postorder, level order

Try your own input
ABCDEFG
CurrentDiscovered / computedAnswer
Stack bottom → top, or queue front → back
Empty
Order
Preorder
Output
—

One tree, four traversal orders. #k under a node is its position in the current output.

InvariantThe three depth-first orders differ only in where the root is output: before, between or after its subtrees. Level order uses a queue, and first in, first out means level by level.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 403, with it.

Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def rob_tree(root) -> int:
    """Largest sum of node values with no parent-child pair both taken."""

    def dfs(node) -> tuple[int, int]:  # (best if node is taken, best if it is not)
        if not node:
            return 0, 0
        lt, ls = dfs(node.left)
        rt, rs = dfs(node.right)
        take = node.val + ls + rs  # children must be skipped
        skip = max(lt, ls) + max(rt, rs)  # children are free to choose
        return take, skip

    return max(dfs(root))
C++
struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};

// {best if node is taken, best if it is not}
pair<long long, long long> robDfs(TreeNode* node) {
    if (!node) return {0, 0};
    auto [lt, ls] = robDfs(node->left);
    auto [rt, rs] = robDfs(node->right);
    long long take = node->val + ls + rs;          // children must be skipped
    long long skip = max(lt, ls) + max(rt, rs);    // children are free to choose
    return {take, skip};
}

// Largest sum of node values with no parent-child pair both taken.
long long robTree(TreeNode* root) {
    auto [take, skip] = robDfs(root);
    return max(take, skip);
}
Java
class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    // Largest sum of node values with no parent-child pair both taken.
    long robTree(TreeNode root) {
        long[] r = dfs(root);
        return Math.max(r[0], r[1]);
    }

    private long[] dfs(TreeNode node) { // {best if node is taken, best if it is not}
        if (node == null) return new long[] {0, 0};
        long[] l = dfs(node.left), r = dfs(node.right);
        long take = node.val + l[1] + r[1]; // children must be skipped
        long skip = Math.max(l[0], l[1]) + Math.max(r[0], r[1]); // children are free to choose
        return new long[] {take, skip};
    }
}
Go
type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// robTree returns the largest sum of node values with no parent-child pair both taken.
func robTree(root *TreeNode) int {
	var dfs func(*TreeNode) (take, skip int)
	dfs = func(node *TreeNode) (int, int) {
		if node == nil {
			return 0, 0
		}
		lt, ls := dfs(node.Left)
		rt, rs := dfs(node.Right)
		take := node.Val + ls + rs        // children must be skipped
		skip := max(lt, ls) + max(rt, rs) // children are free to choose
		return take, skip
	}
	take, skip := dfs(root)
	return max(take, skip)
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Game interval DP: store "mover minus opponent"O(n²) time · O(n) space

For two players taking from either end in turn, both playing well (Predict the Winner, Stone Game): dp[i][j] stores how much more the player to move can get than the opponent on nums[i..j]. After taking an end, the opponent faces the rest, so it is the larger of nums[i] − dp[i+1][j] and nums[j] − dp[i][j−1], and one row is enough. LC 486 (Predict the Winner), LC 877 (Stone Game).

Python
def first_player_wins(nums: list[int]) -> bool:
    """Players take from either end in turn; does the first end with at least as much? (LC 486)"""
    n = len(nums)
    dp = nums[:]  # dp[j] for the current i: best (mover - opponent) on nums[i..j]; i == j: take it
    for i in range(n - 2, -1, -1):
        for j in range(i + 1, n):
            dp[j] = max(nums[i] - dp[j], nums[j] - dp[j - 1])  # take the left end, or the right
    return dp[n - 1] >= 0
C++
// Players take from either end in turn; does the first end with at least as much? (LC 486)
bool firstPlayerWins(const vector<int>& nums) {
    int n = nums.size();
    vector<int> dp = nums;  // dp[j] for the current i: best (mover - opponent) on nums[i..j]; i == j: take it
    for (int i = n - 2; i >= 0; i--)
        for (int j = i + 1; j < n; j++)
            dp[j] = max(nums[i] - dp[j], nums[j] - dp[j - 1]);  // take the left end, or the right
    return dp[n - 1] >= 0;
}
Java
class Solution {
    // Players take from either end in turn; does the first end with at least as much? (LC 486)
    boolean firstPlayerWins(int[] nums) {
        int n = nums.length;
        int[] dp = nums.clone(); // dp[j] for the current i: best (mover - opponent) on nums[i..j]; i == j: take it
        for (int i = n - 2; i >= 0; i--)
            for (int j = i + 1; j < n; j++)
                dp[j] = Math.max(nums[i] - dp[j], nums[j] - dp[j - 1]); // take the left end, or the right
        return dp[n - 1] >= 0;
    }
}
Go
// firstPlayerWins: players take from either end in turn; does the first end with at least as much? (LC 486)
func firstPlayerWins(nums []int) bool {
	n := len(nums)
	dp := append([]int(nil), nums...) // dp[j] for the current i: best (mover - opponent) on nums[i..j]
	for i := n - 2; i >= 0; i-- {
		for j := i + 1; j < n; j++ {
			dp[j] = max(nums[i]-dp[j], nums[j]-dp[j-1]) // take the left end, or the right
		}
	}
	return dp[n-1] >= 0
}
Monotonic-deque DP: the best dp in a windowO(n) time · O(n) space

When each transition takes the best dp among the previous k positions (jumps of at most k steps, constrained subsequence sums), scanning k each time is O(nk); a monotonic deque holding the window's best dp brings it to O(n). LC 1696 (Jump Game VI); LC 1425 (Constrained Subsequence Sum) and LC 862 use the same deque.

Python
from collections import deque


def max_jump_score(nums: list[int], k: int) -> int:
    """From index 0 to n - 1 in jumps of 1..k steps: the best sum of the values landed on (LC 1696)."""
    n = len(nums)
    dp = [0] * n  # dp[i]: best score landing on i
    dp[0] = nums[0]
    dq = deque([0])  # indexes in the last k, dp decreasing: the front is the best place to jump from
    for i in range(1, n):
        if dq[0] < i - k:
            dq.popleft()  # too far back to reach i
        dp[i] = dp[dq[0]] + nums[i]
        while dq and dp[dq[-1]] <= dp[i]:
            dq.pop()  # i is closer and no worse: they will never be the best again
        dq.append(i)
    return dp[-1]
C++
// From index 0 to n - 1 in jumps of 1..k steps: the best sum of the values landed on (LC 1696).
long long maxJumpScore(const vector<int>& nums, int k) {
    int n = nums.size();
    vector<long long> dp(n);  // dp[i]: best score landing on i
    dp[0] = nums[0];
    deque<int> dq{0};  // indexes in the last k, dp decreasing: the front is the best place to jump from
    for (int i = 1; i < n; i++) {
        if (dq.front() < i - k) dq.pop_front();  // too far back to reach i
        dp[i] = dp[dq.front()] + nums[i];
        while (!dq.empty() && dp[dq.back()] <= dp[i]) dq.pop_back();  // i is closer and no worse
        dq.push_back(i);
    }
    return dp[n - 1];
}
Java
class Solution {
    // From index 0 to n - 1 in jumps of 1..k steps: the best sum of the values landed on (LC 1696).
    long maxJumpScore(int[] nums, int k) {
        int n = nums.length;
        long[] dp = new long[n]; // dp[i]: best score landing on i
        dp[0] = nums[0];
        Deque<Integer> dq = new ArrayDeque<>(List.of(0)); // indexes in the last k, dp decreasing
        for (int i = 1; i < n; i++) {
            if (dq.peekFirst() < i - k) dq.pollFirst(); // too far back to reach i
            dp[i] = dp[dq.peekFirst()] + nums[i];
            while (!dq.isEmpty() && dp[dq.peekLast()] <= dp[i]) dq.pollLast(); // i is closer and no worse
            dq.offerLast(i);
        }
        return dp[n - 1];
    }
}
Go
// maxJumpScore: from index 0 to n - 1 in jumps of 1..k steps, the best sum of the values landed on (LC 1696).
func maxJumpScore(nums []int, k int) int {
	n := len(nums)
	dp := make([]int, n) // dp[i]: best score landing on i
	dp[0] = nums[0]
	dq := []int{0} // indexes in the last k, dp decreasing: the front is the best place to jump from
	for i := 1; i < n; i++ {
		if dq[0] < i-k {
			dq = dq[1:] // too far back to reach i
		}
		dp[i] = dp[dq[0]] + nums[i]
		for len(dq) > 0 && dp[dq[len(dq)-1]] <= dp[i] {
			dq = dq[:len(dq)-1] // i is closer and no worse
		}
		dq = append(dq, i)
	}
	return dp[n-1]
}

Why it works

  1. Splitting the state by whether the node is taken makes subtrees independent: if it is taken, its children must be skipped; if not, each child freely takes its better state. The two cases cover every plan.
  2. Post-order ensures both children's results are ready before the node is computed, and each node is computed once, O(n).
  3. Games use the score difference: dp[i][j] is how far the player to move can finish ahead on nums[i..j]. After taking one end, the opponent faces the same problem on the rest, so dp[i][j] = max(nums[i] − dp[i+1][j], nums[j] − dp[i][j−1]).

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
树形 DP 我用后序遍历,每个节点返回一个二元组:选它时的最优值和不选它时的最优值。选了它,两个孩子都只能不选;不选它,每个孩子在两种里取更大的。这样子树互不干扰,每个节点算一次,O(n)。双人博弈我用当前玩家能领先多少分做状态,拿走一端后对手面对的是同样的子问题,减去它的结果即可。
English
For tree DP I go post-order and each node returns a pair: the best value if it is taken and if it is skipped. If it is taken both children must be skipped; if not, each child contributes the larger of its two values. Subtrees stay independent and each node is computed once, so it is O(n). For two-player games I use how far the player to move can finish ahead, because after taking one end the opponent faces the same subproblem and I subtract its result.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. Two players alternately take a number from either end of an array, both optimally. The DP is dp[i][j] = max(a[i] - dp[i+1][j], a[j] - dp[i][j-1]). What is dp[i][j]?
  2. Longest increasing path in a matrix by memoized DFS: why is no visited set needed against walking in circles?
  3. What is the time complexity of this code (n = len(a), tightest bound)?
    from functools import lru_cache
    
    def first_player_margin(a):
        @lru_cache(maxsize=None)
        def go(i, j):
            if i > j:
                return 0
            return max(a[i] - go(i + 1, j), a[j] - go(i, j - 1))
    
        return go(0, len(a) - 1)

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

class TreeNode:

    return max(dfs(root))

Practice by stage

This stop's 6 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 1

#ProblemApproachRating
337House Robber IIIReturn selected and unselected profits for every tree node and combine child results in postorder.

Advanced 5

#ProblemApproachRating
403Frog JumpRecognize that reaching the same stone with different jump lengths changes future reachability and requires another state dimension.
1696Jump Game VIDerive a monotonic-deque optimization from a sliding-window maximum transition, expiring indices rather than comparing original array values.Rating 1954
486Predict the WinnerUse the score difference to represent optimal play by both sides rather than assuming a fixed greedy opponent.
375Guess Number Higher or Lower IIDistinguish worst-case from expected cost and use minimax to explain why the binary-search midpoint need not be cheapest.
1140Stone Game IIInclude the maximum permitted take in the adversarial state, using suffix sums and memoization to express both players' gains.Rating 2035