Divide array into increasing and decreasing subsequence without changing the order | Java 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
import java . util . * ; class GFG { static void Find_Sequence ( int [ ] arr , int n ) { Vector < Integer > inc_arr = new Vector < > ( ) , dec_arr = new Vector < > ( ) ; int flag = 0 ; long inc = - 1 , dec = ( long ) 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 . add ( arr [ i ] ) ; } else { dec = arr [ i ] ; dec_arr . add ( arr [ i ] ) ; } } else if ( inc < arr [ i ] ) { inc = arr [ i ] ; inc_arr . add ( arr [ i ] ) ; } else if ( dec > arr [ i ] ) { dec = arr [ i ] ; dec_arr . add ( arr [ i ] ) ; } else { System . out . println ( - 1 ) ; flag = 1 ; break ; } } if ( flag == 0 ) { for ( int i : inc_arr ) System . out . print ( i + " ▁ " ) ; System . out . println ( ) ; for ( int i : dec_arr ) System . out . print ( i + " ▁ " ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 1 , 3 , 6 , 8 , 2 , 9 , 0 , 10 } ; int n = arr . length ; Find_Sequence ( arr , n ) ; } }