Divide array into increasing and decreasing subsequence without changing the order | C ++ implementation of the approach ; Function to print strictly increasing and strictly decreasing sequence if possible ; Arrays to store strictly increasing and decreasing sequence ; Initializing last element of both sequence ; Iterating through the array ; If current element can be appended to both the sequences ; If next element is greater than the current element Then append it to the strictly increasing array ; Otherwise append it to the strictly decreasing array ; If current element can be appended to the increasing sequence only ; If current element can be appended to the decreasing sequence only ; Else we can not make such sequences from the given array ; Print the required sequences ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Find_Sequence ( int arr [ ] , int n ) { vector < int > inc_arr , dec_arr ; int flag = 0 ; long inc = -1 , dec = 1e7 ; for ( int i = 0 ; i < n ; i ++ ) { if ( inc < arr [ i ] && arr [ i ] < dec ) { if ( arr [ i ] < arr [ i + 1 ] ) { inc = arr [ i ] ; inc_arr . emplace_back ( arr [ i ] ) ; } else { dec = arr [ i ] ; dec_arr . emplace_back ( arr [ i ] ) ; } } else if ( inc < arr [ i ] ) { inc = arr [ i ] ; inc_arr . emplace_back ( arr [ i ] ) ; } else if ( dec > arr [ i ] ) { dec = arr [ i ] ; dec_arr . emplace_back ( arr [ i ] ) ; } else { cout << -1 << endl ; flag = 1 ; break ; } } if ( ! flag ) { for ( auto i = inc_arr . begin ( ) ; i != inc_arr . end ( ) ; i ++ ) cout << * i << " ▁ " ; cout << endl ; for ( auto i = dec_arr . begin ( ) ; i != dec_arr . end ( ) ; i ++ ) cout << * i << " ▁ " ; cout << endl ; } } int main ( ) { int arr [ ] = { 5 , 1 , 3 , 6 , 8 , 2 , 9 , 0 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Find_Sequence ( arr , n ) ; }