- 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
- 63 lines of C++ from the credited upstream file maximum-score-using-exactly-k-pairs.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 8 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 long long maxScore(vector<int>& nums1, vector<int>& nums2, int k) {8 static const auto& NEG_INF = numeric_limits<int64_t>::min();9 10 if (size(nums1) < size(nums2)) {11 swap(nums1, nums2);12 }13 vector<vector<int64_t>> dp(size(nums2) + 1, vector<int64_t>(k + 1, NEG_INF));14 for (int j = 0; j < size(dp); ++j) {15 dp[j][0] = 0;16 }17 vector<vector<int64_t>> new_dp(size(nums2) + 1, vector<int64_t>(k + 1, NEG_INF));18 for (int i = 0; i < size(nums1); ++i) {19 for (int j = 0; j < size(new_dp); ++j) {20 new_dp[j][0] = 0;21 } 22 for (int j = 0; j < size(nums2); ++j) {23 const auto& score = static_cast<int64_t>(nums1[i]) * nums2[j];24 const auto& mx = min({i + 1, j + 1, k});25 for (int c = 0; c < mx; ++c) {26 new_dp[j + 1][c + 1] = max({27 new_dp[j][c + 1],28 dp[j + 1][c + 1],29 dp[j][c] + score30 });31 }32 }33 swap(dp, new_dp);34 }35 return dp.back().back();36 }37};38 394041class Solution2 {42public:43 long long maxScore(vector<int>& nums1, vector<int>& nums2, int k) {44 static const auto& NEG_INF = numeric_limits<int64_t>::min();45 46 vector<vector<int64_t>> dp(size(nums1), vector<int64_t>(size(nums2), NEG_INF));47 vector<vector<int64_t>> new_dp(size(nums1), vector<int64_t>(size(nums2), NEG_INF));48 for (int c = 0; c < k; ++c) {49 for (int i = c; i < size(nums1); ++i) {50 for (int j = c; j < size(nums2); ++j) {51 new_dp[i][j] = max({52 j - 1 >= c ? new_dp[i][j - 1] : NEG_INF,53 i - 1 >= c ? new_dp[i - 1][j] : NEG_INF,54 (c ? dp[i - 1][j - 1] : 0) + static_cast<int64_t>(nums1[i]) * nums2[j]55 });56 }57 }58 swap(dp, new_dp);59 }60 return dp.back().back();61 }62};63