leetcode 718. Maximum Length of Repeated Subarray | 718. 最长重复子数组(动态规划)

题目

https://leetcode.com/problems/maximum-length-of-repeated-subarray/
在这里插入图片描述

题解

Dynamic Programming [Accepted]

参考:官方题解

Intuition and Algorithm

Since a common subarray of A and B must start at some A[i] and B[j], let dp[i][j] be the longest common prefix of A[i:] and B[j:]. Whenever A[i] == B[j], we know dp[i][j] = dp[i+1][j+1] + 1. Also, the answer is max(dp[i][j]) over all i, j.

We can perform bottom-up dynamic programming to find the answer based on this recurrence. Our loop invariant is that the answer is already calculated correctly and stored in dp for any larger i, j.
在这里插入图片描述

class Solution {
    public int findLength(int[] nums1, int[] nums2) {
        int[][] same = new int[nums1.length][nums2.length];
        int max = 0;
        for (int i = 0; i < nums1.length; i++) {
            for (int j = 0; j < nums2.length; j++) {
                if (nums1[i] == nums2[j]) {
                    same[i][j] = 1;
                    if (i > 0 && j > 0) same[i][j] += same[i - 1][j - 1];
                    max = Math.max(max, same[i][j]);
                }
            }
        }
        return max;
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值