Longest Bitonic Subsequence | DP | lbs ( ) returns the length of the Longest Bitonic Subsequence in arr [ ] of size n . The function mainly creates two temporary arrays lis [ ] and lds [ ] and returns the maximum lis [ i ] + lds [ i ] - 1. lis [ i ] == > Longest Increasing subsequence ending with arr [ i ] lds [ i ] == > Longest decreasing subsequence starting with arr [ i ] ; allocate memory for LIS [ ] and initialize LIS values as 1 for all indexes ; Compute LIS values from left to right ; allocate memory for LDS and initialize LDS values for all indexes ; Compute LDS values from right to left for i in reversed ( range ( n - 1 ) ) : loop from n - 2 downto 0 for j in reversed ( range ( i - 1 , n ) ) : loop from n - 1 downto i - 1 ; Return the maximum value of ( lis [ i ] + lds [ i ] - 1 ) ; Driver program to test the above function
def lbs ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE lis = [ 1 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 0 , i ) : NEW_LINE INDENT if ( ( arr [ i ] > arr [ j ] ) and ( lis [ i ] < lis [ j ] + 1 ) ) : NEW_LINE INDENT lis [ i ] = lis [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT lds = [ 1 for i in range ( n + 1 ) ] NEW_LINE INDENT if ( arr [ i ] > arr [ j ] and lds [ i ] < lds [ j ] + 1 ) : NEW_LINE INDENT lds [ i ] = lds [ j ] + 1 NEW_LINE DEDENT DEDENT maximum = lis [ 0 ] + lds [ 0 ] - 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT maximum = max ( ( lis [ i ] + lds [ i ] - 1 ) , maximum ) NEW_LINE DEDENT return maximum NEW_LINE DEDENT arr = [ 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 ] NEW_LINE print " Length ▁ of ▁ LBS ▁ is " , lbs ( arr ) NEW_LINE