- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 59 lines of C++ from the credited upstream file maximum-weight-in-two-bags.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 9 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int maxWeight(vector<int>& weights, int w1, int w2) {8 static const int MAX_W = 300;9 10 vector<bitset<MAX_W + 1>> dp(w1 + 1), new_dp(w1 + 1);11 dp[0][0] = 1;12 for (const auto& w : weights) {13 for (int i = 0; i <= w1; ++i) {14 new_dp[i] = dp[i] | (i - w >= 0 ? dp[i - w] : 0) | (dp[i] << w);15 }16 swap(dp, new_dp);17 }18 int result = 0;19 for (int i = 0; i <= w1; ++i) {20 for (int j = w2; j >= 0; --j) {21 if (dp[i][j]) {22 result = max(result, i + j);23 break;24 }25 }26 }27 return result;28 }29};30 31323334class Solution2 {35public:36 int maxWeight(vector<int>& weights, int w1, int w2) {37 vector<vector<bool>> dp(w1 + 1, vector<bool>(w2 + 1)), new_dp(w1 + 1, vector<bool>(w2 + 1));38 dp[0][0] = true;39 for (const auto& w : weights) {40 for (int i = 0; i <= w1; ++i) {41 for (int j = 0; j <= w2; ++j) {42 new_dp[i][j] = dp[i][j] || (i - w >= 0 && dp[i - w][j]) || (j - w >= 0 && dp[i][j - w]);43 }44 }45 swap(dp, new_dp);46 }47 int result = 0;48 for (int i = 0; i <= w1; ++i) {49 for (int j = w2; j >= 0; --j) {50 if (dp[i][j]) {51 result = max(result, i + j);52 break;53 }54 }55 }56 return result;57 }58};59