My Labels

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

Wednesday, December 25, 2013

Q. Basic fibonaci program using DP

This  is  the  first  program  for  understanding  DP

You  must  be  knowing  Fib(n)=Fib(n-1)+Fib(n-2)

Lets  see  the  function  calls  of  Fib(6)







Here  we  can  see  Fib(4)  is  called  two  times  and  same  goes  with  Fib(3)  and  other  function  calls.  So  we  can  reduce  our  complexity  by  using  arrays  for  storage....

Just  where  there  is  returning  condition i.e Fib(0)=0,,  we  make  Fib[0]=0

and  make  Fib[n]=Fib[n-1]+Fib[n-2]  we  can  avoid  unecessary  calls  to  functions  again  and  again.....

#include<stdio.h>
int main()
{
int n=12;
int fib[12];
fib[0]=0;
fib[1]=1;
for(int k=2;k<n;k++)
{
fib[k]=fib[k-1]+fib[k-2];
}
printf("%d",fib[n-1]);

Please  tell  me  for  any  other  updates in  this  article

Tuesday, December 10, 2013

Q. Find the maximum sum subarray such that no 2 elements are contiguous

INPUT  {5,4,10,40,50,35}
OUTPUT  5+40+35=80

This  thing  is  used  when  basically  we  are  getting  a  recursive  function  and  DP  helps  us  in  reducing  complexity.

We  can  see  here  F(j)={arr[j]+F(j-2)}  as  we  cant  have  consecutive  elements  so  we  take  sum  till   j-2

where  F(i)=  max  subarray  formed  till   the  ith  index  of  array

#include<stdio.h>

int main()
{
 int n=6;
 int arr[6] = {5,4, 10, 40, 50, 35};
 //int arr[5]={3,2,7,10};
 int dp[5];
 dp[0]=arr[0];
 dp[1]=arr[0]>=arr[1]?arr[0]:arr[1];

 for(int k=2;k<n;k++)
 {
 int sum=arr[k]+dp[k-2];
 dp[k]= sum>dp[k-1]?sum:dp[k-1];
 }
 printf("%d",dp[n-1]);
}

I  know  I  may  be  bad  at  explaining  things  so  please  tell  me  if  you  are  unable  to  understand  I  will  try  to  make  content  mare  explainable..

Also  please  tell  if  my  code  is  failing  at  some  point