Unbounded knapsack

Dynamic Programming DP on subsequences Hard
  • The knapsack problem is fundamental in resource allocation tasks and is widely applicable across numerous industries for decision making
  • A fun, practical example is in the world of video game design
  • In games where characters have limited carrying capacity, designers use the knapsack problem to create algorithms that help players automatically select the best items to carry for optimal game outcomes
  • Moreover, this problem is also used in file storage and network data packet transmission to achieve maximum efficiency within certain capacity constraints

Given two integer arrays, val and wt, each of size N, representing 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. The goal is to maximize the sum of the values of the selected items while keeping the total weight within the knapsack's capacity.


An infinite supply of each item can be assumed.

Examples:

Input: val = [5, 11, 13], wt = [2, 4, 6], W = 10

Output: 27

Explanation: Select 2 items with weights 4 and 1 item with weight 2 for a total value of 11+11+5 = 27.

Input: val = [10, 40, 50, 70], wt = [1, 3, 4, 5], W = 8

Output: 110

Explanation: Select items with weights 3 and 5 for a total value of 40 + 70 = 110.

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

Constraints

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

Hints

  • We define dp[w] as the maximum value achievable using items with a knapsack capacity of w. the recurrence relation is: dp[w]=max(dp[w],dp[w−wt[i]]+val[i])
  • Since dp[w] only depends on smaller values, we only need a 1D DP array (dp[W]) instead of O(N × W).

Company Tags

IBM Salesforce AMD Byju's Micron Technology Unity Technologies Zynga Cloudflare Bungie Broadcom American Express Visa GE Healthcare Walmart Snowflake Goldman Sachs Texas Instruments Wayfair Optum DoorDash Mastercard NVIDIA Ubisoft eBay Lyft Google Microsoft Amazon Meta Apple Netflix Adobe