Solution: The 0/1 Knapsack Problem
This review provides a detailed analysis of the different ways to solve The Knapsack Problem.
We'll cover the following...
Solution #1: Brute force
Explanation
We start from the beginning of the weight array and check if the item is within the maximum capacity as done on line 12. If it is within the maximum capacity, we call the knapsack() function recursively with the item and save the result in profit1 (line 13).
Then, we call the function recursively excluding the item and saving the result in the variable profit2 (line 15).
Out of the two, we return the result that has higher profit (as done on line 18).
Let’s draw the recursive calls to see if there are any overlapping subproblems. As we can see, in each recursive call, the profits and weights arrays remain constant, and only the capacity and the current index change. For simplicity, let’s denote capacity with C and current index with n:
Time complexity
The time complexity of the algorithm above is , i.e., exponential, where is the total number of items. This is because we have that many calls. The logic is similar to the one presented in the time complexity calculation of Fibonacci numbers. This is mostly owing to the overlapping subproblems. Let’s see how you can reduce it with a dynamic programming approach.
Solution #2: Top-down dynamic programming approach with memoization
Explanation
The function knapSack makes a lookupTable within the function that stores the maximum value that can be attained with maximum capacity (lines 29-35). This function calls ...