0-1 knapsack problem

mam why my code is not working…

@YASHMATHURIA123
Also the cases will be like:-
if(a[i]<=k) then take for x.
for y, it should also be called recursively, even when a[i]>k so move it outside of the if statement.

One more thing is you should always initialize x and y with ‘0’ since you are using global variable so they may be containing some previous value…

thankyou sir mera code work kar gaya magar mera code global variable declare se nahi chal raha tha magar local variable banna k chal gay aisa kyu

can you please tell me.

@YASHMATHURIA123
see this is a recursive function, so this will be called many time and x and y are updated every time.
So whenever it is called again then it should calculate for very of x and y, but the x is inside a ‘if’ statement so there may be chances that x is not calculated for some recursive call. But you still have some previous value in x.
So it is better to initialize x every time, or take in as a local variable instead of global.

1 Like