Leetcode 718 Solution

This article provides solution to leetcode question 718 (maximum-length-of-repeated-subarray)

https://leetcode.com/problems/maximum-length-of-repeated-subarray

Solution

class Solution { public: int findLength(vector<int>& A, vector<int>& B) { int m = A.size(); int n = B.size();
vector<vector<int>> dp(m, vector<int>(n)); int ans = 0;
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (A[i] == B[j]) dp[i][j] = i > 0 && j > 0 ? dp[i - 1][j - 1] + 1 : 1; else dp[i][j] = 0; ans = max(ans, dp[i][j]); } } return ans; } };