package leetcode;

/**
 * https://leetcode.com/problems/maximum-length-of-repeated-subarray/
 */
public class Problem718 {
    public int findLength(int[] A, int[] B) {
        return findLength(A, B, 0, 0);
    }

    private static int findLength(int[] a, int[] b, int i, int j) {
        if (i == a.length) {
            return 0;
        }
        if (j == b.length) {
            return 0;
        }
        int max = 0;
        if (a[i] == b[j]) {
            int z = findLength(a, b, i + 1, j + 1) + 1;
            max = Math.max(max, z);
        } else {
            int x = findLength(a, b, i, j + 1);
            int y = findLength(a, b, i + 1, j);
            max = Math.max(max, Math.max(x, y));
        }
        return max;
    }

    public static void main(String[] args) {
        Problem718 prob = new Problem718();
        System.out.println(prob.findLength(new int[]{1, 2, 3, 2, 1}, new int[]{3, 2, 1, 4, 7})); // 3
        System.out.println(prob.findLength(new int[]{1, 2, 3, 2, 1}, new int[]{1, 3, 2, 1, 4, 7})); // 3
    }
}

@@ -174,37 +174,232 @@
     
-return findLength(A, B, 0, 0)
+Integer%5B%5D%5B%5D memo = new Integer%5BA.length + 1%5D%5BB.length + 1%5D;%0A        int max = 0;%0A        for (int i = 0; i %3C A.length; i++) %7B%0A            max = Math.max(max, findLength(A, B, i, 0, false, memo));%0A        %7D%0A        return max
 ;%0A  
@@ -467,16 +467,49 @@
 i, int j
+, boolean found, Integer%5B%5D%5B%5D memo
 ) %7B%0A    
@@ -618,32 +618,107 @@
 rn 0;%0A        %7D%0A
+        if (memo%5Bi%5D%5Bj%5D != null) %7B%0A            return memo%5Bi%5D%5Bj%5D;%0A        %7D%0A
         int max 
@@ -766,15 +766,27 @@
     
-int z =
+max = Math.max(max,
  fin
@@ -815,13 +815,26 @@
  + 1
+, true, memo
 ) + 1
+)
 ;%0A  
@@ -843,120 +843,115 @@
     
-    max = Math.max(max, z);%0A        %7D else %7B%0A            int x = findLength(a, b, i, j + 1);%0A            int y =
+%7D else %7B%0A            if (found) %7B%0A                return max;%0A            %7D%0A            max = Math.max(max,
  fin
@@ -965,23 +965,37 @@
 (a, b, i
+, j
  + 1, 
-j
+false, memo)
 );%0A     
@@ -1001,58 +1001,35 @@
     
+%7D%0A
     
-max = Math.max(max, Math.max(x, y));%0A        %7D
+    memo%5Bi%5D%5Bj%5D = max;
 %0A   
@@ -1344,20 +1344,254 @@
  7%7D)); // 3%0A
+        System.out.println(prob.findLength(new int%5B%5D%7B0, 1, 1, 1, 1%7D, new int%5B%5D%7B1, 0, 1, 0, 1%7D)); // 2%0A        System.out.println(prob.findLength(new int%5B%5D%7B0, 0, 0, 0, 0, 0, 1, 0, 0, 0%7D, new int%5B%5D%7B0, 0, 0, 0, 0, 0, 0, 1, 0, 0%7D)); // 9%0A
     %7D%0A%7D%0A

Update problem 718