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 DP [ ] array ; 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
function LongSubarrSeq ( arr1 , arr2 ) { let M = arr1 . length ; let N = arr2 . length ; let maxL = 0 ; let DP = new Array ( M + 1 ) ; for ( var i = 0 ; i < DP . length ; i ++ ) { DP [ i ] = new Array ( 2 ) ; } for ( var i = 0 ; i < DP . length ; i ++ ) { for ( var j = 0 ; j < DP . length ; j ++ ) { DP [ i ] [ j ] = 0 ; } } for ( let i = 1 ; i <= M ; i ++ ) { for ( let j = 1 ; j <= N ; j ++ ) { if ( arr1 [ i - 1 ] == arr2 [ j - 1 ] ) { DP [ i ] [ j ] = 1 + DP [ i - 1 ] [ j - 1 ] ; } else { DP [ i ] [ j ] = DP [ i ] [ j - 1 ] ; } } } for ( let i = 1 ; i <= M ; i ++ ) { for ( let j = 1 ; j <= N ; j ++ ) { maxL = Math . max ( maxL , DP [ i ] [ j ] ) ; } } return maxL ; } let arr1 = [ 4 , 2 , 3 , 1 , 5 , 6 ] ; let arr2 = [ 3 , 1 , 4 , 6 , 5 , 2 ] ; document . write ( LongSubarrSeq ( arr1 , arr2 ) ) ;