LeetCode 718: Maximum Length of Repeated Subarray Solution

Master LeetCode problem 718 (Maximum Length of Repeated Subarray), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming. We can create a 2D array dp where dp[i][j] represents the length of the longest common suffix of subarrays nums1[0, i] and nums2[0, j] that end at nums1[i] and nums2[j] respectively. We iterate through both arrays and update the dp array accordingly. The maximum value in dp will give us the length of the longest common subarray. :

Solution Code

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 718 (Maximum Length of Repeated Subarray)?

This page provides optimized solutions for LeetCode problem 718 (Maximum Length of Repeated Subarray) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 718 (Maximum Length of Repeated Subarray)?

The time complexity for LeetCode 718 (Maximum Length of Repeated Subarray) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 718 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 718 in Java, C++, or Python.

Back to LeetCode Solutions