Longest increasing sequence by the boundary elements of an Array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSequence ( int n , int arr [ ] ) { int l = 0 , r = n - 1 ; int prev = INT_MIN ; int ans = 0 ; while ( l <= r ) { if ( arr [ l ] > prev && arr [ r ] > prev ) { if ( arr [ l ] < arr [ r ] ) { ans += 1 ; prev = arr [ l ] ; l += 1 ; } else { ans += 1 ; prev = arr [ r ] ; r -= 1 ; } } else if ( arr [ l ] > prev ) { ans += 1 ; prev = arr [ l ] ; l += 1 ; } else if ( arr [ r ] > prev ) { ans += 1 ; prev = arr [ r ] ; r -= 1 ; } else { break ; } } return ans ; } int main ( ) { int arr [ ] = { 3 , 5 , 1 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestSequence ( n , arr ) ; return 0 ; }