O(mn) time, O(n) space solution


  • 0
    F
    class Solution {
        public int findLength(int[] A, int[] B) {
            int m = A.length;
            int n = B.length;
            int[] dp = new int[n + 1];
            int res = 0;
            
            for (int i = 0; i <= m; i++) {
                for (int j = n; j >= 0; j--) {
                    if (i == 0 || j == 0 || A[i - 1] != B[j - 1]) {
                        dp[j] = 0;
                    } else {
                        dp[j] = dp[j - 1] + 1; 
                    }
                    
                    res = Math.max(res, dp[j]);
                }
            }
            
            return (res);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.