Problem in code

Whats the problem in my code that its not working? Also can you specify test cases where its failing?

hello @kunal81198
read this carefully->

image

first remove all those packet whose value is -1
and then apply 0-1 knapsack.
check ->

but i have already made a condition about that -1 in if else part in knapscak function. Also its a problem of unbounded knapsack not 0-1

yeah , 0-n knapsack (that was typo)

check input format . …

So are you saying that i should take input if price is -1?

also doesnt this line take care of -1 thing?
if(price[i-1]>0)
dp[i][j]=min(price[i-1]+dp[i][j-weight[i-1]],dp[i-1][j]);

i m talking about input format.

image

why r u reading n elements? N has no role in this problem.
u are given W prices and their weight is i+1 .(read input format)

int n,total_weight;
cin>>n>>total_weight;
int weight[n];
int price[n];
for(int i=0;i<total_weight;i++)
{
cin>>price[i];
}
for(int i=0;i<total_weight;i++)
{
weight[i]=i+1;
}
cout<<Knapsack(weight,price,total_weight,n);

Is this input correct?

why n here? n shold be replaced with total weight

bro 1 test case still failing pls help

image

add this price consition in this if.(becuase these two are must condition if we want to include current weight, otherwise dp[i][j]=dp[i-1][j])

But bro i am including it in the next line if(price[i-1]>0) in line 21

what if this condtion fails,ur code will not update dp[i][j] right?
ideally in that case dp[i][j] shpuld be dp[i-1][j]

so either add dp[i][j] shpuld be dp[i-1][j] by writing a separate else of that if.

or mention price condition in outer if

1 Like

Yes got it bro thanks