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>
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
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
No comments:
Post a Comment