# Knapsack Algorithm

We have given items i1, i2 , ..., in (the item we want to put in our bag) with associated weights w1, w2, ... wn and profit values V1, V2, ... Vn. Now the problem is **how we can maximize the total benefit given a capacity of the bag is W and each item is allowed to be used for 0 or 1 time**?

Generally, there are two **Knapsack problems** first is **fractional knapsack** and second is **0-1 knapsack**. In this article, we are discussing **0-1 knapsack algorithm**. In **fractional knapsack**, you can cut a fraction of object and put in a bag but in 0-1 knapsack either you take it completely or you don’t take it.

In order to solve the **0-1 knapsack problem**, our greedy method fails which we used in the fractional knapsack problem. So the only method we have for this optimization problem is solved using Dynamic Programming, for applying Dynamic programming to this problem we have to do three things in this problem:

- Optimal substructure
- Writing the recursive equation for substructure
- Whether subproblems are repeating or not

Now assume we have **'n'** items **1 2 3 ... N**. I will take an item and observe that there are two ways to consider the item either

- it could be included in knapsack
- or you might not include it in knapsack

Likewise, every element has 2 choices. Therefore we have **2X2X2X2...** Upto **n** choices i.e **2^n choices**.

We have to consider the **2^n solution** to find out the optimal answer but now we have to find that is there any repeating substructure present in the problem so that exempt from examining **2^n solutions**.

The recursive equation for this problem is given below:

knapsack(i,w) = { max( Vi +knapsack(i-1,W-wi) , knapsack(i-1,W) )
0,i=0 & W=0
Knapsack(i-1,W) , wi> W
}

## Algorithm using Bottom up Dynamic Programming:

## C++ Implementation of Knapsack problem

1) Using recursive methodOutput

need an explanation for this answer? contact us directly to get an explanation for this answerOutput