3647. Maximum Weight in Two Bags
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
w1 total weight.
- Bag 2 holds at most
w2 total weight.
Return the maximum total weight that can be packed into the two bags.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public: int maxWeight(vector<int>& weights, int w1, int w2) { vector<vector<bool>> dp(w1 + 1, vector<bool>(w2 + 1, false)); dp[0][0] = true; int res = 0; for(auto& w : weights) { for(int i = w1; i >= 0; i--) { for(int j = w2; j >= 0; j--) { if(i >= w and dp[i-w][j]) dp[i][j] = true, res = max(res, i + j); if(j >= w and dp[i][j-w]) dp[i][j] = true, res = max(res, i + j); } } } return res; } };
|