Leetcode - Middle of the Linked List
Leetcode - Min Stack

Leetcode - Maximum Length of Repeated Subarray

violet posted @ Apr 09, 2020 07:50:24 AM in 算法 with tags Algorithm Golang array DP , 223 阅读

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
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter