Given two integer arrays A
and B
, return the maximum length of an subarray that appears in both arrays.
Example 1:
Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output: 3
Explanation:
The repeated subarray with maximum length is [3, 2, 1].
Note:
- 1 <= len(A), len(B) <= 1000
- 0 <= A[i], B[i] < 100
code:
import java.util.*;
import java.math.*;
import java.lang.*;
import java.io.*;
class Test {
public static void main(String[] args) {
int[] A = {1,2,3,4,5,6};
int[] B = {2,3,4,5,6,7,8};
Test test = new Test();
int a = test.findLength(A,B);
System.out.println(a);
}
public int findLength(int[] A,int[] B) {
int length = 0;
int lenA = A.length;
int lenB = B.length;
int lenM = Math.max(lenA,lenB);
int[][] dp = new int[lenM+1][lenM+1];
for(int i=0;i<lenA;i++)
dp[i][0] = 0;
for(int j=0;j<lenB;j++)
dp[0][j] = 0;
for(int i=1;i<=lenA;i++)
for(int j=1;j<=lenB;j++) {
if(A[i-1]==B[j-1]) {
dp[i][j]=dp[i-1][j-1]+1;
length = Math.max(length, dp[i][j]);
}
}
return length;
}
}