Showing posts with label Dynamic Programming. Show all posts
Showing posts with label Dynamic Programming. Show all posts

Saturday, 16 January 2021

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.

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:

fib(4)fib(3)fib(2)fib(2)fib(1)fib(1)fib(0)fib(0)fib(1)
Recursion tree for calculating Fibonacci numbers


We can clearly see the overlapping subproblem pattern here, fib(2) has been evaluated twice and fib(1) has been evaluated 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 

DP offers two methods to solve a problem.

1. Top-down with Memoization 

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.

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 us now look at some problems solved with Dynamic Programming.

Check out more articles.

 

Fibonacci Numbers Using Dynamic Programming

 The following code illustrates the implementation of Fibonacci Numbers using the Dynamic Programming concept. Here we have used two basic principles of DP that is optimal substructure and overlapping behaviour to solve the problem. 

The time complexity of problem is O(n2) and space complexity is O(n) as we are using a 1-d Array.

//Fibonacci Series using Dynamic Programming 

#include<stdio.h> 

int fib(int n
{
/* Declare an array to store Fibonacci numbers. */

int f[n+2]; // 1 extra to handle case, n = 0 

int i; 



/* 0th and 1st number of the series are 0 and 1*/

f[0] = 0

f[1] = 1



for (i = 2; i <= n; i++) 


    /* Add the previous 2 numbers in the series 

        and store it */

    f[i] = f[i-1] + f[i-2]; 




return f[n]; 




int main () 


int n = 9

printf("%d"fib(n)); 

getchar(); 

return 0

Wednesday, 18 December 2019

C program for 0/1 Knapsack Using Dynamic Programming

#include<stdlib.h>
#include<stdio.h>

int max(int a,int b)
{
    int m=(a>b)?a:b;
    return m;
}

int knap(int n,int v[],int w[],int cap)
{
    int val[n+1][cap+1];
    for(int j=0;j<=cap;j++)
        val[0][j]=0;
    for(int i=1;i<=n;i++)
    {
        for(int j=0;j<=cap;j++)
        {
            if(w[i]<=j)
                val[i][j]=max(val[i-1][j],(v[i]+val[i-1][j-w[i]]));
            else 
                val[i][j]=val[i-1][j];
        }
    }
    return val[n][cap];
}

int main()
{
    int n=3;
    int v[3]={60,100,120};
    int w[3]={10,20,30};
    int cap=50;

    int res=knap(n,v,w,cap);
    printf("The result is %d",res);

    return 0;
}

C program for Matrix Chain Multiplication using Dynamic Programming

#include <stdio.h>
#include <limits.h>

int compute(int ar[],int n)
{
    int m[n][n];
    int i=0;
    for(i=0;i<n;i++)
    {
        m[i][i]=0;  //Cost of multiplying a matrix to itself is 0
    }

    //We have chosen a zero row and zero column redundant 
    int l,j,k;
    int q;
    for(l=2;l<n;l++)  //No of matrix we are multiplying at a time
    {
        for(i=1;i<n-l+1;i++)  //Row variable loop
        {
            j=i+l-1;  //Limit of column reached upto at a time
            m[i][j]=INT_MAX;  //Keeping target cell set to max no. to find the minimum
            for (k=i;k<j;k++)  //Column variable loop
            {
                q=m[i][k]+m[k+1][j]+ar[i-1]*ar[k]*ar[j];
                if(q<m[i][j]) //setting least no. of operation
                {
                    m[i][j]=q;
                }
            }
        }
    }
    return m[1][n-1];
}

int main(void){
    int n;
    printf("\nEnter the no of arrays :- ");
    scanf("%d",&n);
    int ar[n+1];
    int i=0;
    for(;i<n+1;i++)
    {
        printf("Enter dimension: ");
        scanf("%d",&ar[i]);
    }
    printf("\nThe required minimum no. of multiplication operations %d",compute(ar,n+1));
}

C program for max-min using Dynamic Programming

#include <stdlib.h>
#include <stdio.h>

void maxmin(int *a,int l,int u,int *min,int *max)
{
    int lmax,lmin,rmax,rmin,mid;
    //As array has one element then min and max is equal
    if(l==u)
    {
        *max=a[l];
        *min=a[u];
    }
    //We compare both the elements
    else if(u==l+1)
    {
        if(a[l]<a[u])
        {
            *max=a[u];
            *min=a[l];
        }
        else 
        {
            *max=a[l];
            *min=a[u];
        }
    }
    else 
    {
        mid=(l+u)/2;
        //Dividing the array into two subparts
        maxmin(a,l,mid,&lmin,&lmax);
        maxmin(a,mid+1,u,&rmin,&rmax);
        //Now comparing max and min of each left and right subarrays
        *min=(lmin>rmin)?rmin:lmin;
        *max=(lmax>rmax)?lmax:rmax;
    }
}
int main()
{
    int n=10;
    int max,min;
    int ar[n];
    //Allowing the array to take random arbitary elements
    for (int i=0;i<10;i++)
    {
        ar[i]=rand();
    }
    //Call to max min function
    maxmin(ar,0,n-1,&min,&max);
    //Printing the max and min
    printf("Max is %d and min is %d",max,min);
}