Leetcode - Maximum Length of Repeated Subarray
https://leetcode.com/problems/maximum-length-of-repeated-subarray/
Given two integer arrays A
and B
, return the maximum length of an subarray that appears in both arrays.
Example 1:
Input: A: [1,2,3,2,1] B: [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3, 2, 1].
func findLength(A []int, B []int) int { result := 0 dp := make([][]int, len(A)+1) for i := 0; i < len(dp); i++ { dp[i] = make([]int, len(B)+1) } for i := len(A) - 1; i >= 0; i-- { for j := len(B) - 1; j >= 0; j-- { if A[i] == B[j] { dp[i][j] = dp[i+1][j+1] + 1 result = max(result, dp[i][j]) } } } return result } func max(a, b int) int { if a > b { return a } return b }