Search⌘ K
AI Features

Challenge: The 0/1 Knapsack Problem

In this challenge, we'll introduce the famous 'knapsack problem' and solve a coding challenge on it.

Welcome to your first dynamic programming problem! Remember to work your way up to the correct solution. It might help to think of the brute force solution first, then memoize it or tabulate it. The process of coming up with a solution to a problem like this would be similar in a real interview. Remember, you can discuss it with your interviewer and talk out loud while you’re implementing the solution. Good luck!

P.S. Changing the prototype of the given function would result in an error. If the need to change it arises, create another function and call it from the one that is given.

Problem statement

Let’s look at the 0/1 knapsack problem. Imagine that you’re a burglar at a jewelry store with a knapsack. Your goal is to choose a combination of jewelry that results in the most profit. Let’s see how you would code this problem.

Given two integer lists that represent the weights and profits of N items, implement a function knap_sack() that finds a subset of these items which will give us the maximum profit, so that their cumulative weight is not more than a given number capacity. Each item can only be selected once, which means we either skip it or put it in the knapsack.

Input

  1. The profit that can be gained by each piece of the jewelry
  2. The number of pieces of jewelry
  3. The weight of each piece of jewelry
  4. The maximum weight that the knapsack can hold
  5. The length of the array

Output

The maximum profit that can be returned

Sample input

    profit = [60, 100, 120] 
    profits_length = 3
    weight = [10, 20, 30] 
    capacity = 50 # knapsack weight

Sample output

    result = 220

Coding challenge

First, take a close look at this problem and design a step-by-step algorithm before jumping to the implementation. This problem is designed for your practice, so try to solve it on your own first. If you get stuck, you can always refer to the solution provided in the solution section. Good luck!

Python 3.5
def knap_sack(profits, profits_length, weights, capacity):
"""
Finds the maximum value that can be put in a knapsack
:param profits: The profit that can be gained by each item
:param profits_length: The number of pieces of jewelry
:param weights: The weight of each piece of jewelry
:param capacity: The maximum weight that the knapsack can hold
:return: Maximum value that can be put in a knapsack
"""
# Write your code here!
pass