Dynamic Programming

This introductory guide to Dynamic Programming, you will explore the foundational principles of DSA, understand their significance and applications, discover effective strategies for learning, and step-by-step journey for beginners.

Overveiw

Chapters

6 Chapters are there for this module. We will cover all concepts related to Dynamic Programming.

Start learning

Quizs

Quiz on the topics being learnt in this module to enusure your knowlege.

Quiz

Problems

Practice Problems on the topics being covered in this module.

Practice

What is Dynamic Programming (DP)?

Last Updated: 14 Mar, 2024

Dynamic Programming (DP) is defined as a technique that solves some particular types of problems in polynomial time. DP solutions are faster than the exponential brute-force method and can be easily proven correct.

Dynamic Programming is mainly an optimization over plain recursion. Wherever we encounter a recursive solution with repeated calls for the same inputs, Dynamic Programming allows us to optimize by storing the results of subproblems. This avoids redundant computations, thereby reducing time complexities from exponential to polynomial.




Characteristics of Dynamic Programming Algorithm

In general, Dynamic Programming (DP) is one of the most powerful techniques for solving a certain class of problems. It involves an elegant formulation approach, a straightforward thinking process, and simple coding.

Essentially, DP works by solving a problem with a given input and storing the result for future reference, avoiding recomputation. This principle can be summarized as "Remember your Past" :).

A strong indicator for using DP is if the problem can be divided into smaller subproblems, with overlapping subproblems. The Optimal Substructure Property ensures that optimal solutions to these subproblems contribute to the optimal solution of the entire problem.

The solutions to subproblems can be stored in a table or array (memoization) or computed in a bottom-up manner (tabulation) to prevent redundant computation.

Dynamic Programming can be implemented using a recursive algorithm, where solutions to subproblems are found recursively, or using an iterative algorithm, where solutions are derived by working through subproblems in a specific order.

Dynamic Programming works based on the following principles:

  1. Characterize the structure of the optimal solution by building a mathematical model.
  2. Recursively define the value of the optimal solution.
  3. Using a bottom-up approach, compute the value of the optimal solution for each possible subproblem.
  4. Construct the optimal solution for the original problem using information computed in the previous step.



Techniques to Solve Dynamic Programming Problems

  1. Top-Down (Memoization): Break down the given problem and check if it has already been solved by looking up the saved answer. If solved, return the saved result; if not, solve it and save the result. This approach is intuitive and easy to implement. It is referred to as Memoization.
  2. Bottom-Up (Tabulation): Analyze the problem to determine the order in which subproblems should be solved, starting from the simplest subproblem and working up to the original problem. This ensures that all required subproblems are solved before tackling the main problem. It is referred to as Dynamic Programming.
Types of Dynamic Programming Approaches:

Dynamic Programming algorithms can be categorized into two main types based on their approach:

  • Top-Down (Memoization): Starts solving the problem by breaking it down into smaller subproblems and storing the results of these subproblems. This approach often uses recursion to solve the subproblems.
  • Bottom-Up (Tabulation): Solves the problem iteratively by solving all subproblems first and using the results to build up to the solution of the original problem. This approach typically uses loops to iterate through the subproblems.



Tabulation vs Memoization

There are two different ways to store the values so that the values of a sub-problem can be reused. Here, we will discuss two patterns of solving dynamic programming (DP) problems:

  • Tabulation: Bottom-Up
  • Memoization: Top-Down

Before getting to the definitions of the above two terms, consider the following statements:

  • Version 1: I will study the theory of DP from GeeksforGeeks, then I will practice some problems on classic DP and hence I will master DP.
  • Version 2: To Master DP, I would have to practice Dynamic problems and practice problems – Firstly, I would have to study some theories of DP from GeeksforGeeks.

Both versions convey the same idea but differ in the way of conveying the message, which is analogous to the difference between Bottom-Up and Top-Down DP. Version 1 relates to Bottom-Up DP, while Version 2 relates to Top-Down DP.

Comparison of Tabulation and Memoization
Criteria Tabulation Memoization
State transition relation Difficult to think Easy to think
Code complexity Gets complicated when many conditions are required Easy and less complicated
Speed Fast, directly accesses previous states from the table Slow due to a lot of recursive calls and return statements
Subproblem solving If all subproblems must be solved at least once, outperforms memoized algorithm by a constant factor Only solves subproblems that are definitely required
Table entries Starting from the first entry, all entries are filled one by one Not all entries are necessarily filled; filled on demand
Approach Iterative approach (dynamic programming) Recursive approach



How to solve a Dynamic Programming Problem?

To dynamically solve a problem, we need to check two necessary conditions:

  1. Overlapping Subproblems: When the solutions to the same subproblems are needed repetitively for solving the actual problem. The problem is said to have the overlapping subproblems property.
  2. Optimal Substructure Property: If the optimal solution of the given problem can be obtained by using optimal solutions of its subproblems, then the problem is said to have the optimal substructure property.

Steps to solve a Dynamic programming problem:

  1. Identify if it is a Dynamic programming problem.
  2. Decide a state expression with the Least parameters.
  3. Formulate state and transition relationships.
  4. Do tabulation (or memorization).

1) How to classify a problem as a Dynamic Programming algorithm Problem?

Typically, problems that involve maximizing or minimizing certain quantities, counting problems under certain conditions, or probability problems can be solved using Dynamic Programming. All dynamic programming problems satisfy the overlapping subproblems property, and most classic DP problems also satisfy the optimal substructure property.

2) Deciding the state:

Dynamic programming problems are primarily concerned with defining states and their transitions. The choice of the state must be made carefully to minimize state space and optimize solution complexity.

3) Formulating a relation among the states:

The most challenging part of solving a DP problem involves defining relationships between states. This step requires intuition, observation, and practice to identify how solutions to larger problems can be built from solutions to smaller subproblems.

Example:

Given 3 numbers {1, 3, 5}, find the total number of ways to form a number N using these numbers (allowing repetitions and different arrangements).

  • State definition: Let state(N) denote the total number of arrangements to form N using {1, 3, 5}.
  • Transition relation: state(N) = state(N-1) + state(N-3) + state(N-5)

3.1) How to Compute the state?

Compute state(N) by adding the results of smaller subproblems:

  • state(N) = state(N-1) + state(N-3) + state(N-5)

4) Adding memoization or tabulation for the state

Memoization optimizes the recursive approach by storing previously computed results:

// Initialize to -1 
int dp[MAXN];

// This function returns the number of 
// arrangements to form 'n' 
int solve(int n) 
{ 
    // base case 
    if (n < 0) 
        return 0; 
    if (n == 0) 
        return 1; 

    // Checking if already calculated 
    if (dp[n]!=-1) 
        return dp[n]; 

    // Storing the result and returning 
    return dp[n] = solve(n-1) + solve(n-3) + solve(n-5); 
}

Memoization reduces time complexity by storing and reusing intermediate results, avoiding redundant calculations.

Time Complexity: O(n), as previously computed results are reused.

Auxiliary Space: O(n), due to recursion call stack and storage of computed results.




How to solve Dynamic Programming problems through Example?

To dynamically solve a problem, we need to check two necessary conditions:

  1. Overlapping Subproblems: When the solutions to the same subproblems are needed repetitively for solving the actual problem. The problem is said to have the overlapping subproblems property.
  2. Optimal Substructure Property: If the optimal solution of the given problem can be obtained by using optimal solutions of its subproblems, then the problem is said to have the optimal substructure property.

Steps to solve a Dynamic programming problem:

  1. Identify if it is a Dynamic programming problem.
  2. Decide a state expression with the Least parameters.
  3. Formulate state and transition relationships.
  4. Do tabulation (or memorization).

1) How to classify a problem as a Dynamic Programming algorithm Problem?

Typically, problems that involve maximizing or minimizing certain quantities, counting problems under certain conditions, or probability problems can be solved using Dynamic Programming. All dynamic programming problems satisfy the overlapping subproblems property, and most classic DP problems also satisfy the optimal substructure property.

2) Deciding the state:

Dynamic programming problems are primarily concerned with defining states and their transitions. The choice of the state must be made carefully to minimize state space and optimize solution complexity.

3) Formulating a relation among the states:

The most challenging part of solving a DP problem involves defining relationships between states. This step requires intuition, observation, and practice to identify how solutions to larger problems can be built from solutions to smaller subproblems.

Example:

Given 3 numbers {1, 3, 5}, find the total number of ways to form a number N using these numbers (allowing repetitions and different arrangements).

  • State definition: Let state(N) denote the total number of arrangements to form N using {1, 3, 5}.
  • Transition relation: state(N) = state(N-1) + state(N-3) + state(N-5)

3.1) How to Compute the state?

Compute state(N) by adding the results of smaller subproblems:

  • state(N) = state(N-1) + state(N-3) + state(N-5)

4) Adding memoization or tabulation for the state

Memoization optimizes the recursive approach by storing previously computed results:

// Initialize to -1 
  int dp[MAXN];
  
  // This function returns the number of 
  // arrangements to form 'n' 
  int solve(int n) 
  { 
      // base case 
      if (n < 0) 
          return 0; 
      if (n == 0) 
          return 1; 
  
      // Checking if already calculated 
      if (dp[n]!=-1) 
          return dp[n]; 
  
      // Storing the result and returning 
      return dp[n] = solve(n-1) + solve(n-3) + solve(n-5); 
  }
  

Memoization reduces time complexity by storing and reusing intermediate results, avoiding redundant calculations.

Time Complexity: O(n), as previously computed results are reused.

Auxiliary Space: O(n), due to recursion call stack and storage of computed results.

Optimized approach:

Using a bottom-up approach to calculate the Fibonacci sequence, which optimizes both time and space complexities:

// Function for calculating the nth Fibonacci number 
  int fibo(int n) 
  { 
      int prevPrev, prev, curr; 
    
      // Storing the base cases 
      prevPrev = 0; 
      prev = 1; 
      curr = 1; 
    
      // Using the bottom-up approach 
      for (int i = 2; i <= n; i++) { 
          curr = prev + prevPrev; 
          prevPrev = prev; 
          prev = curr; 
      } 
    
      // Returning the final answer 
      return curr; 
  } 
    
  // Drivers code 
  int main() 
  { 
      int n = 5; 
    
      // Function Call 
      cout << fibo(n); 
      return 0; 
  }
  

This optimized approach reduces the space complexity to O(1) by storing only the necessary previous two values to compute the next Fibonacci number iteratively.