Java 19 lines dfs+memo with line-by-line explanation easy to understand
\n\n\nclass Solution {\n    int M = (int)1e9+7;\n    public int maxSum(int[] nums1, int[] nums2) {\n        Map<Integer, List<Integer>> map= new HashMap<>();\n 
![image](https://assets.leetcode.com/users/images/8287b1db-1420-4f8a-8eef-974ec8b0f5c4_1596344125.888696.png)\n\n```\nclass Solution {\n    int M = (int)1e9+7;\n    public int maxSum(int[] nums1, int[] nums2) {\n        Map<Integer, List<Integer>> map= new HashMap<>();\n        for (int i=0; i<nums1.length-1; i++)\n            map.computeIfAbsent(nums1[i], k -> new LinkedList<>()).add(nums1[i+1]);\n        for (int i=0; i<nums2.length-1; i++)\n            map.computeIfAbsent(nums2[i], k -> new LinkedList<>()).add(nums2[i+1]);\n        Map<Integer, Long> memo = new HashMap<>();\n        return (int)Math.max(greedy(nums1[0], map, memo)%M, greedy(nums2[0], map, memo)%M);\n    }\n    \n    long greedy(int cur, Map<Integer, List<Integer>> map, Map<Integer, Long> memo){\n        if (memo.containsKey(cur)) return memo.get(cur);\n        if (!map.containsKey(cur)) return cur;\n        long maxSum=0;\n        for (int next: map.get(cur)){\n            maxSum = Math.max(maxSum, greedy(next, map, memo));\n        }\n        maxSum+=cur;\n        memo.put(cur, maxSum);\n        return maxSum;\n    }\n}\n```\nHappy Coding!
[]