Chapter 15 - Dynamic Programming
When the same subproblems come back again and again, compute each one once and store the result.
This page is the entry point of chapter 15 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.
The idea
Dynamic programming applies when the answer to a problem is built from the answers to smaller versions of the same problem, and those smaller versions overlap. Top-down, we write the natural recursion and memoize it. Bottom-up, we fill a table from the smallest cases. Very often, only the previous row or the two previous values are needed, and the memory drops from \(O(n^2)\) to \(O(n)\), or from \(O(n)\) to \(O(1)\).
When to reach for it
- Count the number of ways to do something.
- Minimum or maximum cost under constraints.
- “Longest” subsequence or substring, and choices to take or leave items (knapsack).
In Rust
vec![vec![0; cols + 1]; rows + 1]builds a table with an extra row and column for the base cases.- Using
i32::MAXas “impossible” breaks on+ 1: usesaturating_add, orOption<i32>. - For memoization, a
Vec<Option<T>>indexed by the state is faster and simpler than aHashMapwhen the state is a small integer.
Problems in this chapter
- p311 - Climbing Stairs: Climbing Stairs (Dynamic Programming) solved in Rust: count the distinct ways to climb n steps, taking 1 or 2 steps at a time.
- p316 - Minimum Coin Combination: Minimum Coin Combination (Dynamic Programming) solved in Rust: the minimum number of coins needed to reach a target amount.
- p321 - Matrix Pathways: Matrix Pathways (Dynamic Programming) solved in Rust: count the paths from the top-left to the bottom-right corner, moving only down or right.
- p325 - Neighborhood Burglary: Neighborhood Burglary (Dynamic Programming) solved in Rust: the most money we can rob from a street without robbing two adjacent houses.
- p329 - Longest Common Subsequence: Longest Common Subsequence (Dynamic Programming) solved in Rust: find the length of the longest common subsequence (LCS) of two strings.
- p334 - Longest Palindrome in a String: Longest Palindrome in a String (Dynamic Programming), solved in Rust. Return the longest palindromic substring within a given string.
- p339 - Maximum Subarray Sum: Maximum Subarray Sum (Dynamic Programming) solved in Rust: the largest sum of a contiguous subarray of an array of i32.
- p345 - 0/1 Knapsack: 0/1 Knapsack (Dynamic Programming) solved in Rust: pick items, each with a weight and a value, to maximize the total value within a capacity.
- bonus132 - Largest Square in a Matrix: Largest Square in a Matrix (Dynamic Programming), solved in Rust. Determine the area of the largest square of 1’s in a binary matrix.
Other chapters
All the chapters, with every problem, are listed on the series page.