Knapsack in 1-D
Standard · Write code · about 15 min
Item i weighs weights[i] and is worth profits[i]. Each item can be packed at most once.
Return the largest total worth that fits in a bag of weight capacity. Use one array of capacity + 1 entries.
Example 1
Input:
[[1,3,4],[15,20,30],4]
Output:
35
Pack the items weighing 1 and 3.
Example 2
Input:
[[2,3,4,5],[3,4,5,6],5]
Output:
7
Weights 2 and 3: 3 + 4 = 7.
Constraints
- 1 ≤ weights.length = profits.length ≤ 1,000
- 1 ≤ weights[i] ≤ 1,000
- 0 ≤ capacity ≤ 1,000
- 1 ≤ profits[i] ≤ 1,000
Learn the idea first: Space optimization: rolling rows and variables, a visual lesson.
More Space optimization: rolling rows and variables problems
- Why iterate in reverse Warm-up
- Optimize unique paths Standard
- House robber in two variables Standard
- Trace one-row knapsack Standard
- Edit distance in O(min(m, n)) space Challenge