718. Maximum Length of Repeated Subarray

TC: O(mn)
SC: O(mn)
class Solution {
    public int findLength(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int[][] dp = new int[m+1][n+1];
        
        int result = 0;
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (nums1[i-1] == nums2[j-1]) {
                    dp[i][j] = dp[i-1][j-1]+1;
                    result = Math.max(result, dp[i][j]);
                }
            }
        }
        return result;
    }
}

/*
longest common subarray

TC: O(mn)
SC: O(mn)

xxxi
xxxj

if (a[i] == b[j]) dp[i][j] = dp[i-1][j-1]+1 
else 0


xxxi   a[i] != b[j], means no futher subarray meets, need recaculate
xxxj 

because there is 0 in the process, so we need take the max one in the process, so use a varible to record the max value

*/

Last updated