exited with code=3221225725 in 0.995 seconds
Only one test case passing and in offline compiler giving exited with code=3221225725 in 0.995 seconds
Hi harsh I think the sum can be much greater than 1001 so I would recommend to increase the second dimension of the dp table …rest all seems fine to me for now … please try this
now producing segmentation fault
Make this
dp[length_of_array+1][sum_of_all_weights+1]
That’s it.
#include<iostream>
#include<cstring>
using namespace std;
int p=0;
int dp[1005][1005];
int knapsack(int n,int s,int*w,int*v){
int ans=0;
if(n<=0 || s<=0){
return ans;
}
if(dp[n][s]!=-1){
return dp[n][s];
}
int a,b;
if(s-w[n-1]>=0){
a=v[n-1]+knapsack(n-1,s-w[n-1],w,v);
}
b=knapsack(n-1,s,w,v);
ans=max(a,b);
dp[n][s]=ans;
return ans;
}
int main() {
int n,s;
cin>>n>>s;
int w[n];
int v[n];
for(int i=0;i<n;i++){
cin>>w[i];
}
for(int i=0;i<n;i++){
cin>>v[i];
p+=v[i];
}
p++;
for(int i=0;i<1005;i++){
for(int j=0;j<1005;j++){
dp[i][j]= -1;
}
}
cout<<knapsack(n,s,w,v);
return 0;
}
Try this
only 1st test case passing
change the base case as
if(n==0)
{
if(s==0) return 0;
else return -1e7;
}
}
This is because u know that only when s==0 then only we can say that it has been correctly distributed right.Else we can just return a huge negative number denoting that it is a wrong path.
Now try it.