0-N Knapsack Optimisation

Current solution: https://ide.codingblocks.com/s/99112
I have optimized it to O(n^2)
How can I optimize it to O(n).
Please tell the top down approach.
I am still getting the correct answer as n is 10^3. I want it in O(n).

1 Like

Hello Pratham, if you’re familiar with DP, try to implement it in your code. It would reduce the complexity of your code. The repeating conditions would not be executed again but the already stored values would be returned from the DP array.

Hi Ajinkya,
I have already implemented DP in the solution to reduce it from exponential to n^2. I want to optimize it further.
Please check my code.

My friend, the best complexity you can get after using DP in the knapsack problem is O(n*W), where W stands for weight. Iteratively or recursively, you can’t get O(n) with DP.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.