Given a string str, the task is to find the minimum numbers of substrings that the given string S can be split into, such that each substring is monotonously increasing or decreasing.
Examples:
Input: str = "abcdcba"
Output: 2
Explanation:
The string can be split into a minimum of 2 monotonous substrings {"abcd"(increasing), "cba"(decreasing)}
Input: str = "aeccdhba"
Output: 3
Explanation:
The generated substrings are {"ae", "ccdh", "ba"}
Approach: Follow the steps below to solve the problem:
- Initialize a variable ongoing = 'N' to keep track of order of current sequence.
- Iterate over the string and for each character, follow the steps below:
- If ongoing == 'N':
- If curr_character < prev_character then update ongoing with D(Non-Increasing).
- Otherwise, if curr_character > prev_character, then update ongoing with I(Non-Decreasing).
- Otherwise, update ongoing with N(neither Non-Increasing nor Non-Decreasing).
- Otherwise, if ongoing == 'I':
- If curr_character > prev_character then update ongoing with I.
- Otherwise, if curr_character < prev_character then update ongoing with N and increment answer.
- Otherwise, update ongoing with I.
- else do the following steps:
- If curr_character < prev_character then update ongoing with D.
- Otherwise, if curr_character > prev_character then update ongoing with N and increment answer.
- Otherwise, update ongoing with D.
- Finally, print answer+1 is the required answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)