1. 程式人生 > >[leetcode]718. Maximum Length of Repeated Subarray

[leetcode]718. Maximum Length of Repeated Subarray

[leetcode]718. Maximum Length of Repeated Subarray


Analysis

今天被微博上的孫藝興bot笑死,哈哈哈哈哈—— [每天刷題並不難0.0]

Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.
在這裡插入圖片描述

Explanation:

dp[i][j] denotes the maximum common subarrary ending with A[i] and B[j],
thus dp[i][j] = A[i-1]==B[j-1]?1+dp[i-1][j-1]:0

Implement

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