Minimize splits to generate monotonous Substrings from given String | 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
def minReqSubstring ( s , n ) : NEW_LINE INDENT ongoing = ' N ' NEW_LINE count , l = 0 , len ( s ) NEW_LINE for i in range ( 1 , l ) : NEW_LINE INDENT if ongoing == ' N ' : NEW_LINE INDENT if s [ i ] < s [ i - 1 ] : NEW_LINE INDENT ongoing = ' D ' NEW_LINE DEDENT elif s [ i ] == s [ i - 1 ] : NEW_LINE INDENT ongoing = ' N ' NEW_LINE DEDENT else : NEW_LINE INDENT ongoing = ' I ' NEW_LINE DEDENT DEDENT elif ongoing == ' I ' : NEW_LINE INDENT if s [ i ] > s [ i - 1 ] : NEW_LINE INDENT ongoing = ' I ' NEW_LINE DEDENT elif s [ i ] == s [ i - 1 ] : NEW_LINE INDENT ongoing = ' I ' NEW_LINE DEDENT else : NEW_LINE INDENT ongoing = ' N ' NEW_LINE count += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if s [ i ] < s [ i - 1 ] : NEW_LINE INDENT ongoing = ' D ' NEW_LINE DEDENT elif s [ i ] == s [ i - 1 ] : NEW_LINE INDENT ongoing = ' D ' NEW_LINE DEDENT else : NEW_LINE INDENT ongoing = ' N ' NEW_LINE count += 1 NEW_LINE DEDENT DEDENT DEDENT return count + 1 NEW_LINE DEDENT S = " aeccdhba " NEW_LINE n = len ( S ) NEW_LINE print ( minReqSubstring ( S , n ) ) NEW_LINE