Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

0-1 Knapsack Problem

Medium Acceptance 50.00% Points 30.00

Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible.

Note: The constraint here is we can either put an item completely into the bag or cannot put it at all [It is not possible to put a part of an item into the bag].

Examples
Example 1

Example 1

Input: W = 5, profit[] = [10, 40, 30, 50], weight[] = [5, 4, 6, 3]

Output: 50

Explanation: Choose the last item (profit 50, weight 3) for a total value of 50.

Example 2

Example 2

Input: W = 4, profit[] = [1, 2, 3], weight[] = [4, 5, 1]

Output: 3

Explanation: Choose the last item, which weighs 1 unit and has a profit of 3.

Hints
Hint 1
Expected Time Complexity: O(n * W)
Hint 2
Expected Auxiliary Space: O(W)
Constraints
  • 2 <= profit.size() = weight.size() <= 10^3
  • 1 <= W <= 10^3
  • 1 <= profit[i] <= 10^3
  • 1 <= weight[i] <= 10^3
Companies
Amazon Microsoft Visa Oracle Flipkart + 1 more
Topics
Array Dynamic Programming
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions