Skip to content

Commit a94eb5e

Browse files
authored
DP, utilize data from last iteration
1 parent 9827f56 commit a94eb5e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public int findLength(int[] A, int[] B) {
3+
int m = A.length, n = B.length;
4+
int max = 0;
5+
6+
7+
// // 2D matrix, dp[i+1][j+1] meaning longest same subarray ending at A[i], B[j]
8+
// int[][] dp = new int[m+1][n+1];
9+
// for(int i = 0; i < m; i++) {
10+
// for(int j = 0; j < n; j++) {
11+
// dp[i+1][j+1] = A[i] == B[j] ? dp[i][j] + 1: 0;
12+
// max = Math.max(dp[i+1][j+1], max);
13+
// }
14+
// }
15+
16+
// 1D array, going from backwards to utilize data from i-1
17+
int[] dp = new int[n+1];
18+
for(int i = 0; i < m; i++) {
19+
for(int j = n-1; j >= 0; j--) {
20+
dp[j+1] = A[i] == B[j] ? dp[j] + 1: 0;
21+
max = Math.max(dp[j+1], max);
22+
}
23+
}
24+
25+
return max;
26+
}
27+
}

0 commit comments

Comments
 (0)