Longest subarray of an array which is a subsequence in another array | Function to find the length of the longest subarray in arr1 which is a subsequence in arr2 ; Length of the array arr1 ; Length of the array arr2 ; Length of the required longest subarray ; Initialize DParray ; Traverse array arr1 ; Traverse array arr2 ; arr1 [ i - 1 ] contributes to the length of the subarray ; Otherwise ; Find the maximum value present in DP ; Return the result ; Driver Code ; Function call to find the length of the longest required subarray
def LongSubarrSeq ( arr1 , arr2 ) : NEW_LINE INDENT M = len ( arr1 ) ; NEW_LINE N = len ( arr2 ) ; NEW_LINE maxL = 0 ; NEW_LINE DP = [ [ 0 for i in range ( N + 1 ) ] for j in range ( M + 1 ) ] ; NEW_LINE for i in range ( 1 , M + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( arr1 [ i - 1 ] == arr2 [ j - 1 ] ) : NEW_LINE INDENT DP [ i ] [ j ] = 1 + DP [ i - 1 ] [ j - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT DP [ i ] [ j ] = DP [ i ] [ j - 1 ] ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( M + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT maxL = max ( maxL , DP [ i ] [ j ] ) ; NEW_LINE DEDENT DEDENT return maxL ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 4 , 2 , 3 , 1 , 5 , 6 ] ; NEW_LINE arr2 = [ 3 , 1 , 4 , 6 , 5 , 2 ] ; NEW_LINE print ( LongSubarrSeq ( arr1 , arr2 ) ) ; NEW_LINE DEDENT