LeetCode718 Maximum Length of Repeated Subarray

Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.

actually, it remains me of another series of problems which invloves like finding the longest substring that has non repeated character in this, or each of the character can appears k times at most.
well, this kinds of problem is not the same, or even similar to the problems we are gonna discussed today.

the current problem needs to be solved in dp. because, you can sense from the problem: instead of return the result subarray, we need to return that length;
so we have dp as the 2d array, and dp[i][j] represents to the longest common postfix if A only have A[0:i-1] and B only have B[0:j-1]
and we need to get the maximum of the whole 2D array.
the subcase for this problem is also very simple:
when A[i-1]== B[i-1], then dp[i][j] = dp[i-1][j-1] + 1;
and when they are not the same, then we do nothing.

//given two int array. return the length of longest repeated subarray.
//attention: the subarray is consecutive.

//let's try the binary search with naive check, the main idea is:
//use binary search idea to assume the length of longest common subarray.
//it's like: let say the number is definate a num from 0 to min(a.len, b.len), we just need to use binary search to find it.

//now, let's thinking about DP
class Solution {
    public int findLength(int[] A, int[] B) {
        int m = A.length;
        int n = B.length;
        int[][] dp = new int[m+1][n+1];//dp[i][j] stands for the length of common array of A and B. not the max, but why? and what exactly is "length of common array of A and B" means? because there may be not just 1 common array.
        //so dp actually means: the longest common postfix of A[:i-1] and B[:j-1], so when we get dp[m][n], it actually means A 和B整体字符串的最长公共后缀。 并不是我们要求的A和B最长公共连续子序列。
        
        int max = 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] = dp[i-1][j-1] +1;
                    if (dp[i][j] > max) {
                        max = dp[i][j];//why do we have to get the gloabl maximum for whole 2D dp?
                    }
                }//if not the same, then stays 0
            }
        }
        return max; //
    }
    
}

the code is pretty simple

posted @ 2020-05-17 07:53  EvanMeetTheWorld  阅读(10)  评论(0)    收藏  举报