[Java] dfs+memo
\nclass Solution {\n    Map<Integer,Integer>map1=new HashMap<>();\n    Map<Integer,Integer>map2=new HashMap<>();\n    int mod=1000000007;\n    long dp[][][];\n 
```\nclass Solution {\n    Map<Integer,Integer>map1=new HashMap<>();\n    Map<Integer,Integer>map2=new HashMap<>();\n    int mod=1000000007;\n    long dp[][][];\n    public int maxSum(int[] A, int[] B) {\n        for(int i=0;i<A.length;i++){\n            map1.put(A[i],i);\n        }\n        for(int j=0;j<B.length;j++){\n            map2.put(B[j],j);\n        }\n        \n        \n        dp=new long[Math.max(A.length,B.length)][2][2];\n        for(int i=0;i<dp.length;i++){\n            for(int j=0;j<dp[0].length;j++){\n                Arrays.fill(dp[i][j],-1);\n            }\n        }\n\n        long res=Math.max(dfs(A,B,0,0,0),dfs(A,B,0,1,0));\n        return (int)(res%mod);\n    }\n    \n    public long dfs(int A[],int B[],int index,int state,int used){\n        \n        if(state==0){\n            if(index>=A.length)return 0;\n        }else{\n            if(index>=B.length)return 0;\n        }\n        \n        long res=0;\n        \n        if(dp[index][state][used]!=-1)return dp[index][state][used];\n        \n        if(state==0){\n            int cur=A[index];\n            if(map2.containsKey(cur)){\n               if(used==0){\n                   res=Math.max(res,cur+dfs(A,B,map2.get(cur),1,1));\n               }\n            }\n            if(used==0)res=Math.max(res,cur+dfs(A,B,index+1,state,0));\n            else res=Math.max(res,dfs(A,B,index+1,state,0));\n        }else{\n            int cur=B[index];\n            if(map1.containsKey(cur)){\n                if(used==0){\n                    res=Math.max(res,cur+dfs(A,B,map1.get(cur),0,1));\n                }\n            }\n            if(used==0)res=Math.max(res,cur+dfs(A,B,index+1,state,0));\n            else res=Math.max(res,dfs(A,B,index+1,state,0));\n        }\n        dp[index][state][used]=res;\n        return res;\n    }\n}\n```
[]