Log In Sign Up
Day 33

Day 33: The Knapsack Problem

33/60 Days

The Knapsack Problem #

Welcome to Day 33 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore the Knapsack Problem, a fundamental problem in combinatorial optimization and a classic example of dynamic programming.

What is the Knapsack Problem? #

The Knapsack Problem is an optimization problem where we need to select items from a set, each with a weight and a value, to maximize the total value while keeping the total weight within a given limit.

There are two main variants of the Knapsack Problem:

  1. 0/1 Knapsack Problem: Each item can be included only once or not at all.
  2. Unbounded Knapsack Problem: Each item can be included any number of times.

We’ll focus on the 0/1 Knapsack Problem in this lesson.

Problem Statement #

Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack.

Naive Recursive Approach #

Let’s start with a naive recursive implementation:

 1def knapsack_naive(W, wt, val, n):
 2    # Base Case
 3    if n == 0 or W == 0:
 4        return 0
 5
 6    # If weight of the nth item is more than Knapsack capacity W,
 7    # then this item cannot be …