Happy Coding

This blog is for my memorandum about programming and English.

Happy Coding

This blog is for my memorandum

leetcode 718. Maximum Length of Repeated Subarray

Question

Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays. https://leetcode.com/problems/maximum-length-of-repeated-subarray/

Code

class Solution {
public:
    int findLength(vector<int>& A, vector<int>& B) {
        // dp[i][j] will be the maximum length of subarray which ends with A[i] and B[j]
        // ex) 
// A: [1,2,3,2,1]
// B: [3,2,1,4,7]
        // dp [4][1] =  2;
        // if A[i+1] == B[j+1] dp[i+1][j+1] = dp[i][j] + 1  
        // else dp[i+1][j+1] = 0;
        // Time O(mn);
        // Space O(mn);
        vector<vector<int> > dp = vector<vector<int> >(A.size() + 1, vector<int>(B.size()  + 1, 0));

        int ans = 0;
        for(int i = 0; i < A.size(); i++) {
            for(int j = 0; j < B.size(); j++) {
                if(A[i] == B[j]) {
                    if(i - 1 < 0 || j - 1 < 0 ) {
                        dp[i][j] = 1;
                    } else {
                        dp[i][j] = dp[i-1][j-1]  + 1;
                        
                    }
                } else {
                    dp[i][j] = 0;
                }
                ans = max(dp[i][j], ans);
            }
        }

        return ans;
        
        
    }
};