Minimize splits to generate monotonous Substrings from given String | Java Program to implement the above approach ; Function to return final result ; Initialize variable to keep track of ongoing sequence ; If current sequence is neither increasing nor decreasing ; If prev char is greater ; If prev char is same ; Otherwise ; If current sequence is Non - Decreasing ; If prev char is smaller ; If prev char is same ; Update ongoing ; Otherwise ; Update ongoing ; Increase count ; If current sequence is Non - Increasing ; If prev char is greater , then update ongoing with D ; If prev char is equal , then update current with D ; Otherwise , update ongoing with N and increment count ; Return count + 1 ; Driver Code
import java . util . * ; class GFG { static int minReqSubstring ( String s , int n ) { char ongoing = ' N ' ; int count = 0 , l = s . length ( ) ; for ( int i = 1 ; i < l ; i ++ ) { if ( ongoing == ' N ' ) { if ( s . charAt ( i ) < s . charAt ( i - 1 ) ) { ongoing = ' D ' ; } else if ( s . charAt ( i ) == s . charAt ( i - 1 ) ) { ongoing = ' N ' ; } else { ongoing = ' I ' ; } } else if ( ongoing == ' I ' ) { if ( s . charAt ( i ) > s . charAt ( i - 1 ) ) { ongoing = ' I ' ; } else if ( s . charAt ( i ) == s . charAt ( i - 1 ) ) { ongoing = ' I ' ; } else { ongoing = ' N ' ; count += 1 ; } } else { if ( s . charAt ( i ) < s . charAt ( i - 1 ) ) { ongoing = ' D ' ; } else if ( s . charAt ( i ) == s . charAt ( i - 1 ) ) { ongoing = ' D ' ; } else { ongoing = ' N ' ; count += 1 ; } } } return count + 1 ; } public static void main ( String [ ] args ) { String S = " aeccdhba " ; int n = S . length ( ) ; System . out . print ( minReqSubstring ( S , n ) ) ; } }