/** 最长公共子数组 b/w 2 个数组
a = [2,3,4,5,6,7,8],b = [6,7,8,4,5,2,3]
答案 = 6,7,8
基本上创建一个 2d arr 并且如果元素匹配 dp[i][j] = 1 + dp[i-1][j-1];
如果 dp[i][j] > maxLen,更新 maxLen 并存储索引现在我们有了 maxLen,子数组将从 (index - maxLen) 到索引。
*/
int[] finMaxCommon(int[] a, int[] b){
int m = a.length, n = b.length, maxLen = 0;
int[][] dp = new int[m+1][n+1];
// i want a 0th row why? m->out of bounds; comparing i-1; i->1 then i-1 will be 0
for (int i = 1; i<=m; i++){
for(int j = 1; j<=n; j++){
if(a[i-1] == b[j-1]) {
dp[i][j] = 1 + dp[i-1][j-1];
maxLen = Math.max(maxLen, dp[i][j]);
}
}
}
// endIndex = 6, 3, a[6-3+1], a[6]
return new int[]{a[endIndex-maxLen+1], [endIndex]};
}
dry run
0,6,7,8,4,5,2,3
0, 0 //
2, 1 // (2,2) i = 1, j = 6 1 + dp[0][5]
3, 2 // (3,3) i = 2, j = 7 1 + dp[1][6]
4,
5,
6, 1
7, 2
8, 3