Approach Today’s daily is quite strait forward, the optimal structure is presented so we can leverage DP.
For maxProd([idx1 ..], [idx2 ..]), we can split into subproblems:
Take idx1 & idx2 for SP, and don’t do SP for the rest -> nums[idx1] * nums[idx2] Take idx1 & idx2 for SP, and try to add with next solution -> nums[idx1] * nums[idx2] + maxProd([idx1+1 ..], [idx2+1 ..]) Let idx1 pair with others -> maxProd([idx1 ..], [idx2+1 ..]) Let idx2 pair with others -> maxProd([idx1+1 ..], [idx2 ..]) Notice that for situation 2, 3, 4, the need to make sure that at least one element is paired (we cannot have empty pairs) Code class Solution { public: int maxDotProduct(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(); int n = nums2.size(); memo.assign(m, vector<int>(n, -1)); return traverse(nums1, nums2, 0, 0); } int traverse(const vector<int>& nums1, const vector<int>& nums2, int idx1, int idx2) { if(idx1 == nums1.size() || idx2 == nums2.size()) return INT_MIN; if(memo[idx1][idx2] != -1) return memo[idx1][idx2]; int maxSP = INT_MIN; maxSP = max(nums1[idx1]*nums2[idx2], maxSP); int nextSP = traverse(nums1, nums2, idx1+1, idx2+1); if(nextSP != INT_MIN) maxSP = max(nums1[idx1]*nums2[idx2] + nextSP, maxSP); nextSP = traverse(nums1, nums2, idx1, idx2+1); if(nextSP != INT_MIN) maxSP = max(maxSP, nextSP); nextSP = traverse(nums1, nums2, idx1+1, idx2); if(nextSP != INT_MIN) maxSP = max(maxSP, nextSP); memo[idx1][idx2] = maxSP; return maxSP; } vector<vector<int>> memo; };