Maximum Weight in Two Bags Problem
Description
LeetCode Problem 3647.
You are given an integer array weights and two integers w1 and w2 representing the maximum capacities of two bags.
Each item may be placed in at most one bag such that:
- Bag 1 holds at most
w1total weight. - Bag 2 holds at most
w2total weight.
Return the maximum total weight that can be packed into the two bags.
Example 1:
Input: weights = [1,4,3,2], w1 = 5, w2 = 4
Output: 9
Explanation:
- Bag 1: Place weights[2] = 3 and weights[3] = 2 as 3 + 2 = 5 <= w1
- Bag 2: Place weights[1] = 4 as 4 <= w2
- Total weight: 5 + 4 = 9
Example 2:
Input: weights = [3,6,4,8], w1 = 9, w2 = 7
Output: 15
Explanation:
- Bag 1: Place weights[3] = 8 as 8 <= w1
- Bag 2: Place weights[0] = 3 and weights[2] = 4 as 3 + 4 = 7 <= w2
- Total weight: 8 + 7 = 15
Example 3:
Input: weights = [5,7], w1 = 2, w2 = 3
Output: 0
Explanation:
No weight fits in either bag, thus the answer is 0.
Constraints:
1 <= weights.length <= 1001 <= weights[i] <= 1001 <= w1, w2 <= 300
Solution
Approach: Dynamic Programming
This is a 0/1 knapsack with two bags. Let f[j][k] be the largest total weight we can put into bag 1 (capacity j) and bag 2 (capacity k) using the items processed so far.
For each item of weight x, an item can go into bag 1 (if x <= j), into bag 2 (if x <= k), or into neither:
f[j][k] = max(f[j][k], f[j - x][k] + x)whenx <= jf[j][k] = max(f[j][k], f[j][k - x] + x)whenx <= k
The table only depends on the previous item, so we keep a single 2D array and loop over j and k downward, so that each item is used at most once. The answer is f[w1][w2].
Complexity: O(n * w1 * w2) time and O(w1 * w2) extra space, where n is the number of items.
class Solution:
def maxWeight(self, weights: List[int], w1: int, w2: int) -> int:
f = [[0] * (w2 + 1) for _ in range(w1 + 1)]
for x in weights:
for j in range(w1, -1, -1):
row = f[j]
new = row
if x <= j: # put the item into bag 1
new = [a if a > b + x else b + x for a, b in zip(row, f[j - x])]
if x <= w2: # put the item into bag 2 (uses the old row)
new = new[:x] + [a if a > b + x else b + x for a, b in zip(new[x:], row)]
f[j] = new
return f[w1][w2]