C++ O(m + n) top-down dp with memoization
\nclass Solution {\n    unordered_map<int, int> pos1, pos2;\n    unordered_map<int, long long> out1, out2; \n    long long dfs1(int idx, vector<int>& nums1, vec
```\nclass Solution {\n    unordered_map<int, int> pos1, pos2;\n    unordered_map<int, long long> out1, out2; \n    long long dfs1(int idx, vector<int>& nums1, vector<int>& nums2) {\n        if (idx < 0) {\n            return 0;\n        }\n        if (out1.find(idx) != out1.end()) {\n            return out1[idx];\n        }\n        long long result = dfs1(idx - 1, nums1, nums2) + nums1[idx];\n        if (pos2.find(nums1[idx]) != pos2.end()) {\n            long long r2 = dfs2(pos2[nums1[idx]] - 1, nums1, nums2) + nums1[idx];\n            result = max(result, r2);\n        }\n        out1[idx] = result;\n        return result;\n    }\n    long long dfs2(int idx, vector<int>& nums1, vector<int>& nums2) {\n        if (idx < 0) {\n            return 0;\n        }\n        if (out2.find(idx) != out2.end()) {\n            return out2[idx];\n        }\n        long long result = dfs2(idx - 1, nums1, nums2) + nums2[idx];\n        if (pos1.find(nums2[idx]) != pos1.end()) {\n            long long r2 = dfs1(pos1[nums2[idx]] - 1, nums1, nums2) + nums2[idx];\n            result = max(result, r2);\n        }\n        out2[idx] = result;\n        return result;\n    }\npublic:\n    int maxSum(vector<int>& nums1, vector<int>& nums2) {\n        for (int i = 0; i < nums1.size(); i++) {\n            pos1[nums1[i]] = i;\n        }\n        for (int i = 0; i < nums2.size(); i++) {\n            pos2[nums2[i]] = i;\n        }\n        long long result = max(dfs1(nums1.size() - 1, nums1, nums2), dfs2(nums2.size() - 1, nums1, nums2));\n        return result % 1000000007;\n    }\n};\n```
[]