Learn Dynamic Programming Basics for Coding Interviews Introduction to Dynamic Programming

Author : usitvhd
Publish Date : 2021-03-18 09:42:41


Learn Dynamic Programming Basics for Coding Interviews Introduction to Dynamic Programming

Dynamic Programming (DP) is an algorithmic technique for solving an optimization problem by breaking it down into simpler subproblems and utilizing the fact that the optimal solution to the overall problem depends upon the optimal solution to its subproblems.

Let’s take the example of the Fibonacci numbers. As we all know, Fibonacci numbers are a series of numbers in which each number is the sum of the two preceding numbers. The first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, and 8, and they continue on from there.

If we are asked to calculate the nth Fibonacci number, we can do that with the following equation,

Fib(n) = Fib(n-1) + Fib(n-2), for n > 1

As we can clearly see here, to solve the overall problem (i.e. Fib(n)), we broke it down into two smaller subproblems (which are Fib(n-1) and Fib(n-2)). This shows that we can use DP to solve this problem.
Characteristics of Dynamic Programming
Before moving on to understand different methods of solving a DP problem, let’s first take a look at what are the characteristics of a problem that tells us that we can apply DP to solve it.
1. Overlapping Subproblems
Subproblems are smaller versions of the original problem. Any problem has overlapping sub-problems if finding its solution involves solving the same subproblem multiple times. Take the example of the Fibonacci numbers; to find the fib(4), we need to break it down into the following sub-problems:
We can clearly see the overlapping subproblem pattern here, as fib(2) has been called twice and fib(1) has been called three times.
2. Optimal Substructure Property
Any problem has optimal substructure property if its overall optimal solution can be constructed from the optimal solutions of its subproblems. For Fibonacci numbers, as we know,

Fib(n) = Fib(n-1) + Fib(n-2)

This clearly shows that a problem of size ‘n’ has been reduced to subproblems of size ‘n-1’ and ‘n-2’. Therefore, Fibonacci numbers have optimal substructure property.
Dynamic Programming Methods
There are two ways to solve a Dynamic Programming problem:
1. Top-down with Memoization

 

https://aftb.org.uk/advert/east-final-umass-lowell-vs-massachusetts-live-stream-east-mens-ice-hockey-championship-free/

 

https://sars.snowproportal.com/advert/east-hockey-final-umass-lowell-vs-massachusetts-live-stream-east-mens-ice-hockey-championship-free/

 

https://azoptometricsociety.com/advert/east-hockey-final-umass-lowell-vs-massachusetts-live-stream-east-mens-ice-hockey-championship-free/

 

https://irl29er.com/advert/east-hockey-final-umass-lowell-vs-massachusetts-live-stream-east-mens-ice-hockey-championship-free/


https://irl29er.com/advert/hockey-east-mens-ice-hockey-championship-2021-live-stream-massachusetts-vs-umass-lowell-free/


https://azoptometricsociety.com/advert/hockey-east-mens-ice-hockey-championship-2021-live-stream-massachusetts-vs-umass-lowell-free/


https://sars.snowproportal.com/advert/hockey-east-mens-ice-hockey-championship-2021-live-stream-massachusetts-vs-umass-lowell-free/


https://aftb.org.uk/advert/hockey-east-mens-ice-hockey-championship-2021-live-stream-massachusetts-vs-umass-lowell-free/


https://blog.goo.ne.jp/indaxsfree/e/e465d970626b639fbef23d48b64f8b5b


https://www.deviantart.com/hjfgfg/journal/GitLab-licensed-its-technology-to-new-independent-873593478


https://www.thewyco.com/general/gitlab-licensed-its-technology-to-new-independent-chinese-company-18-03-2021

https://blog.goo.ne.jp/indaxsfree/e/5f6415f0f792dff781492c70629ebb68

 

https://paiza.io/projects/Tz76e5oO2A8DXV19lzbGMA


https://caribbeanfever.com/photo/albums/chinese-company


https://velog.io/@sdf/GitLab-licensed-its-technology-to-new-independent-Chinese-company

In this approach, we try to solve the bigger problem by recursively finding the solution to smaller sub-problems. Whenever we solve a sub-problem, we cache its result so that we don’t end up solving it repeatedly if it’s called multiple times. Instead, we can just return the saved result. This technique of storing the results of already solved subproblems is called Memoization.

We’ll see this technique in our example of Fibonacci numbers. First, let’s see the non-DP recursive solution for finding the nth Fibonacci number:

#include<bits/stdc++.h>
using namespace std;

#include <iostream>

class Fibonacci {

public:
  virtual int CalculateFibonacci(int n) {
    if (n < 2) {
      return n;
    }
    return CalculateFibonacci(n - 1) + CalculateFibonacci(n - 2);
  }
};

int main(int argc, char *argv[]) {
  Fibonacci *fib = new Fibonacci();
  cout << "5th Fibonacci is ---> " << fib->CalculateFibonacci(5) << endl;
  cout << "6th Fibonacci is ---> " << fib->CalculateFibonacci(6) << endl;
  cout << "7th Fibonacci is ---> " << fib->CalculateFibonacci(7) << endl;

  delete fib;
}

As we saw above, this problem shows the overlapping subproblems pattern, so let’s make use of memoization here. We can use an array to store the already solved subproblems (see the changes in the highlighted lines).

#include<bits/stdc++.h>
using namespace std;

#include <iostream>
#include <vector>

class Fibonacci {

public:
  virtual int CalculateFibonacci(int n) {
    vector<int> memoize(n + 1, 0);
    return CalculateFibonacciRecursive(memoize, n);
  }

  virtual int CalculateFibonacciRecursive(vector<int> &memoize, int n) {
    if (n < 2) {
      return n;
    }
     // if we have already solved this subproblem, simply return the result from the cache
    if(memoize[n] != 0)
      return memoize[n];
      
    memoize[n] = CalculateFibonacciRecursive(memoize, n - 1) + CalculateFibonacciRecursive(memoize, n - 2);
    return memoize[n];
  }
};

int main(int argc, char *argv[]) {
  Fibonacci *fib = new Fibonacci();
  cout << "5th Fibonacci is ---> " << fib->CalculateFibonacci(5) << endl;
  cout << "6th Fibonacci is ---> " << fib->CalculateFibonacci(6) << endl;
  cout << "7th Fibonacci is ---> " << fib->CalculateFibonacci(7) << endl;

  delete fib;
}


2. Bottom-up with Tabulation

Tabulation is the opposite of the top-down approach and avoids recursion. In this approach, we solve the problem “bottom-up” (i.e. by solving all the related sub-problems first). This is typically done by filling up an n-dimensional table. Based on the results in the table, the solution to the top/original problem is then computed.

Tabulation is the opposite of Memoization, as in Memoization we solve the problem and maintain a map of already solved sub-problems. In other words, in memoization, we do it top-down in the sense that we solve the top problem first (which typically recurses down to solve the sub-problems).

Let’s apply Tabulation to our example of Fibonacci numbers. Since we know that every Fibonacci number is the sum of the two preceding numbers, we can use this fact to populate our table.

Here is the code for our bottom-up dynamic programming approach:

#include<bits/stdc++.h>
using namespace std;

#include <iostream>
#include <vector>

class Fibonacci {

public:
  virtual int CalculateFibonacci(int n) {
    if (n==0) return 0;
    vector<int> dp(n + 1);
    dp[0] = 0;
    dp[1] = 1;
    for (int i = 2; i <= n; i++) {
      dp[i] = dp[i - 1] + dp[i - 2];
    }
    return dp[n];
  }
};

int main(int argc, char *argv[]) {
  Fibonacci *fib = new Fibonacci();
  cout << "5th Fibonacci is ---> " << fib->CalculateFibonacci(5) << endl;
  cout << "6th Fibonacci is ---> " << fib->CalculateFibonacci(6) << endl;
  cout << "7th Fibonacci is ---> " << fib->CalculateFibonacci(7) << endl;

  delete fib;
}



Category : news

Form over how and when to get more schools open amid the coronavirus pandemic, with Republicans seizing on confusion

Form over how and when to get more schools open amid the coronavirus pandemic, with Republicans seizing on confusion

- Form over how and when to get more schools open amid the coronavirus pandemic, with Republicans seizing on confusion


Dutch election: PM Mark Rutte claims victory and fourth term

Dutch election: PM Mark Rutte claims victory and fourth term

- Victory hands Mr Rutte a mandate to form a new coalition government led by his centre-right liberal VVD party, with a fourth term as prime minister...


Fast and Furious 9 Will Air This Year

Fast and Furious 9 Will Air This Year

- Fast and Furious 9 is confirmed to air this year, to be precise in June 2021. Welcoming the release, Universal has released a trailer for the new film


Hire Assignment Help Service Provider to Have Stress Free A College Life

Hire Assignment Help Service Provider to Have Stress Free A College Life

- We all expect college life to be a bag full of excitement. You will have so many new people to meet, different events to attend, and various other opportunities that you have always wanted to do. But,