0 and 1 Knapsack

Dynamic Programming DP on subsequences Hard

Given two integer arrays, val and wt, each of size N, which represent the values and weights of N items respectively, and an integer W representing the maximum capacity of a knapsack, determine the maximum value achievable by selecting a subset of the items such that the total weight of the selected items does not exceed the knapsack capacity W.


Each item can either be picked in its entirety or not picked at all (0-1 property). The goal is to maximize the sum of the values of the selected items while keeping the total weight within the knapsack's capacity.

Examples:

Input: val = [60, 100, 120], wt = [10, 20, 30], W = 50

Output: 220

Explanation: Select items with weights 20 and 30 for a total value of 100 + 120 = 220.

Input: val = [10, 40, 30, 50], wt = [5, 4, 6, 3], W = 10

Output: 90

Explanation: Select items with weights 4 and 3 for a total value of 40 + 50 = 90.

Input: val = [20, 5, 10, 40, 15, 25], wt = [1, 2, 3, 8, 7, 4], W = 10

Constraints

  • 1 ≤ N ≤ 500
  • 1 ≤ W ≤ 1000
  • 1 ≤ wt[i] ≤ 500
  • 1 ≤ val[i] ≤ 500

Hints

  • "Define dp[i][w] as the maximum value achievable using the first i items with a knapsack capacity of w. the recurrence relation is: dp[i][w]=max(dp[i−1][w],dp[i−1][w−wt[i]]+val[i])(if wt[i]≤w) "
  • "Instead of a full dp[n][W] table, we can use a 1D array (dp[W]) and iterate backward (right to left): dp[w]=max(dp[w],dp[w−wt[i]]+val[i]) We iterate from W down to wt[i] to prevent overwriting values."

Company Tags

Medtronic Ubisoft Nutanix Cerner Walmart Bungie Cloudflare Western Digital Qualcomm HCL Technologies Etsy Unity Technologies Philips Healthcare Visa Ernst & Young Rakuten Instacart Morgan Stanley Shopify Wayfair Stripe Roblox Siemens Healthineers Broadcom Pinterest Google Microsoft Amazon Meta Apple Netflix Adobe