Divide array into increasing and decreasing subsequence without changing the order | 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
function Find_Sequence ( arr , n ) { let inc_arr = [ ] , dec_arr = [ ] ; let flag = 0 ; let inc = - 1 , dec = 1e7 ; for ( let i = 0 ; i < n ; i ++ ) { if ( inc < arr [ i ] && arr [ i ] < dec ) { if ( arr [ i ] < arr [ i + 1 ] ) { inc = arr [ i ] ; inc_arr . push ( arr [ i ] ) ; } else { dec = arr [ i ] ; dec_arr . push ( arr [ i ] ) ; } } else if ( inc < arr [ i ] ) { inc = arr [ i ] ; inc_arr . push ( arr [ i ] ) ; } else if ( dec > arr [ i ] ) { dec = arr [ i ] ; dec_arr . push ( arr [ i ] ) ; } else { document . write ( - 1 ) ; flag = 1 ; break ; } } if ( flag == 0 ) { document . write ( " " ) ; for ( let i in inc_arr ) document . write ( inc_arr [ i ] + " " ) ; document . write ( " " ) ; document . write ( " " ) ; for ( let i in dec_arr ) document . write ( dec_arr [ i ] + " " ) ; document . write ( " " ) ; } } let arr = [ 5 , 1 , 3 , 6 , 8 , 2 , 9 , 0 , 10 ] ; let n = arr . length ; Find_Sequence ( arr , n ) ;