Dynamic Programming (DP) is a technique used to solve tricky problems in various fields. It shines when a problem involves making repeated calculations for the same smaller problem. Think of it like a shortcut. It helps us avoid doing the same work over and over again, saving us time and effort.
DP has a reputation for being a very difficult topic. In this book, we'll introduce you to Dynamic Programming through several problem walkthroughs, as this topic is best learned through practice.
The process of DP works in three phases:
There are two main ways to approach a dynamic programming problem:
Efficiency in dynamic programming (DP) problems can vary significantly depending on the implementation strategy. Without memoization, the complexity of solving DP problems can be exponential, often described as O(2^n)
, due to the need to recompute results for overlapping subproblems. However, when memoization is employed, the time complexity generally improves to O(N)
if the problem has a linear number of states or O(N^2)
if the problem states form a two-dimensional space. Both iterative and memoized recursive solutions share the same time complexity.
Dynamic Programming (DP) is particularly effective when solving problems that require optimizing specific criteria or accumulating results over several computations. This includes scenarios where you need to determine the minimum or maximum value, assess possibilities (true/false), optimize a particular outcome, calculate totals, or count distinct ways to achieve a goal.
Avoid DP When the problem asks for all possible solutions without optimization (use combinatorial techniques like backtracking instead).
DP might remind you of another problem-solving strategy called "divide and conquer." Both involve breaking a problem into smaller pieces. However, there's a key difference:
In the following assignments, we'll use several problems to demonstrate how to solve them using DP, both top-down (recursively) and bottom-up (iteratively). Once you understand the solution for one approach, the other one will seem more manageable.