3647. Maximum Weight in Two Bags π
Description
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] = 3andweights[3] = 2as3 + 2 = 5 <= w1 - Bag 2: Place
weights[1] = 4as4 <= 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] = 8as8 <= w1 - Bag 2: Place
weights[0] = 3andweights[2] = 4as3 + 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
Solutions
Solution 1: Dynamic Programming
Thinking
Each item may go into a bag of capacity \(w_1\), a bag of capacity \(w_2\), or neither. That is a two-dimensional \(0\)-\(1\) knapsack. \(n\le 100\) and \(w\le 300\) allow a compressed \(f[j][k]\).
\(f[j][k]\) is the best total when the residual capacities are \(j\) and \(k\). Capacities are scanned backwards so an item is used at most once.
For weight \(x\), try \(f[j-x][k]+x\) and \(f[j][k-x]+x\). The answer is \(f[w_1][w_2]\).
We define \(f[i][j][k]\) to represent the maximum total weight when placing the first \(i\) items into two bags, where bag 1 has a maximum capacity of \(j\) and bag 2 has a maximum capacity of \(k\). Initially, \(f[0][j][k] = 0\), indicating that no items can be placed in the bags.
The state transition equation is:
where \(w_i\) represents the weight of the \(i\)-th item.
The final answer is \(f[n][w1][w2]\), where \(n\) is the number of items.
We notice that the state transition equation only depends on the previous layer's state, so we can compress the three-dimensional DP array into a two-dimensional DP array. When enumerating \(j\) and \(k\), we use reverse traversal.
Time complexity \(O(n \times w1 \times w2)\), space complexity \(O(w1 \times w2)\). Where \(n\) is the length of the array \(\textit{weights}\).
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |