Longest increasing sequence by the boundary elements of an Array | Python3 program to print the longest increasing subsequence from the boundary elements of an array ; Function to return the length of Longest Increasing subsequence ; Set pointers at both ends ; Stores the recent value added to the subsequence ; Stores the length of the subsequence ; Check if both elements can be added to the subsequence ; Check if the element on the left can be added to the subsequence only ; Check if the element on the right can be added to the subsequence only ; If none of the values can be added to the subsequence ; Driver code ; Length of array
import sys NEW_LINE def longestSequence ( n , arr ) : NEW_LINE INDENT l = 0 NEW_LINE r = n - 1 NEW_LINE prev = - sys . maxsize - 1 NEW_LINE ans = 0 NEW_LINE while ( l <= r ) : NEW_LINE INDENT if ( arr [ l ] > prev and arr [ r ] > prev ) : NEW_LINE INDENT if ( arr [ l ] < arr [ r ] ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ l ] NEW_LINE l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ r ] NEW_LINE r -= 1 NEW_LINE DEDENT DEDENT elif ( arr [ l ] > prev ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ l ] NEW_LINE l += 1 NEW_LINE DEDENT elif ( arr [ r ] > prev ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ r ] NEW_LINE r -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 5 , 1 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestSequence ( n , arr ) ) NEW_LINE