Longest Consecuetive Subsequence when only one insert operation is allowed | Function to return the length of longest consecuetive subsequence after inserting an element ; Variable to find maximum value of the array ; Calculating maximum value of the array ; Declaring the DP table ; Variable to store the maximum length ; Iterating for every value present in the array ; Recurrence for dp [ val ] [ 0 ] ; No value can be inserted before 1 , hence the element value should be greater than 1 for this recurrance relation ; Recurrence for dp [ val ] [ 1 ] ; Maximum length of consecutive sequence ending at 1 is equal to 1 ; Update the ans variable with the new maximum length possible ; Return the ans ; Input array
function LongestConsSeq ( arr , N ) { let maxval = 1 ; for ( let i = 0 ; i < N ; i += 1 ) { maxval = Math . max ( maxval , arr [ i ] ) ; } let dp = new Array ( maxval + 1 ) ; for ( let i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 2 ) ; for ( let j = 0 ; j < 2 ; j ++ ) dp [ i ] [ j ] = 0 ; } let ans = 1 ; for ( let i = 0 ; i < N ; i += 1 ) { dp [ arr [ i ] ] [ 0 ] = ( 1 + dp [ arr [ i ] - 1 ] [ 0 ] ) ; if ( arr [ i ] >= 2 ) dp [ arr [ i ] ] [ 1 ] = Math . max ( 1 + dp [ arr [ i ] - 1 ] [ 1 ] , 2 + dp [ arr [ i ] - 2 ] [ 0 ] ) ; else dp [ arr [ i ] ] [ 1 ] = 1 ; ans = Math . max ( ans , dp [ arr [ i ] ] [ 1 ] ) ; } return ans ; } let arr = [ 2 , 1 , 4 , 5 ] ; let N = arr . length ; document . write ( LongestConsSeq ( arr , N ) ) ;