What is Dynamic programming?
An algorithm design method that splits a problem into smaller subproblems and records their answers in a table for reuse, avoiding repeated computation of the same thing. It is used for the knapsack problem, minimum-coin change, the longest common subsequence, shortest paths and more.
Japanese name: 動的計画法
Dynamic programming appears in 3 practice questions across 1 topic, including Data Structures and Algorithms.
Field: Data Structures and Algorithms
Memoization and filling in tables
There are two ways to implement it: memoization (top-down), which keeps the recursive form but remembers computed results, and the bottom-up approach, which fills a table starting from the smallest subproblems. For the 0/1 knapsack problem, for example, the table holds “the maximum value achievable using items up to i within capacity c” and is filled by taking the larger of including or excluding each item. For n items and capacity W, this takes O(nW). The minimum-coin problem can likewise be solved by tabulating the minimum number of coins for each amount from 0 up to the target.
How it differs from greedy algorithms, and applications
A greedy algorithm simply picks the choice that looks best at each moment and moves on, so it is fast but not optimal for some problems. Paying 8 yen with 1-, 4- and 6-yen coins, the greedy algorithm uses three coins, 6 + 1 + 1, while dynamic programming finds two, 4 + 4. Dynamic programming is widely used, for example for edit distance and the longest common subsequence of strings (as in the diff command), DNA sequence alignment, the Viterbi algorithm in speech recognition, and the Floyd-Warshall algorithm for shortest paths between all pairs of vertices.
FAQ
How does dynamic programming differ from divide and conquer?
Both split a problem into subproblems, but in divide-and-conquer algorithms such as merge sort the subproblems do not overlap, so there is no need to record answers. Dynamic programming differs in recording and reusing answers when the same subproblems appear many times.
What are the weaknesses of dynamic programming?
It needs memory and work in proportion to the size of the table. The O(nW) of the knapsack problem is proportional to the value of the capacity W, so it becomes impractical when W is very large. Memory can be reduced by recording only what is needed or keeping only the previous row of the table.