oneby7

2-D Dynamic Programming Knapsack

555. Unbounded Knapsack

Medium

You are given n kinds of items and a bag that holds at most capacity units of weight. An item of kind i is worth val[i] and weighs wt[i]. There is no limit on the number of items of each kind, so you can put the same kind in the bag as many times as you like, or leave it out.

Return the largest total value of items you can put in the bag. Their total weight must be at most capacity, but the bag does not have to be full. Items cannot be cut: each one goes in whole or not at all.

Example 1

Input: val = [18, 25, 8], wt = [3, 4, 5], capacity = 10

Output: 61

Explanation: Two items of kind 0 and one of kind 1 weigh 3 + 3 + 4 = 10 and are worth 18 + 18 + 25 = 61. Kind 1 is worth the most per unit of weight, but two of them leave 2 units that no item fits in.

Example 2

Input: val = [9, 20], wt = [4, 6], capacity = 11

Output: 29

Explanation: One item of each kind weighs 10 and is worth 29. Every weight is even, so the bag can never be filled to exactly 11, and it does not have to be.

Example 3

Input: val = [1000000000, 5] wt = [2, 10000] capacity = 9999

Output: 4999000000000

Explanation: Kind 1 weighs more than the bag holds, so it never fits. Kind 0 fits 4999 times, using 9998 units of weight.

Check your understanding

Work out the answer for this input before you write any code.

val = [14, 16, 3], wt = [4, 5, 7], capacity = 11

Constraints

  • 1 ≤ n ≤ 1000
  • val.length = wt.length = n
  • 1 ≤ val[i] ≤ 109
  • 1 ≤ wt[i] ≤ 104
  • 1 ≤ capacity ≤ 104

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.