Editorial
Let and be the number of s and s, respectively.
If or , the string is already monochrome, so the answer is .
If , we can delete the whole string in one operation, so the answer is .
Now assume and both characters exist. Let the more frequent character be the majority character. Convert the majority character to and the other character to . Let the resulting array be , and let its total sum be . Then .
A deletable substring is exactly a substring with sum . Therefore, no sequence of operations changes the total sum . Since the final string must be monochrome, it must consist of exactly majority characters.
Thus, the problem becomes the following.
Keep some majority characters and divide all other characters into contiguous zero-sum segments. Minimize the number of deleted segments.
Define prefix sums as follows.
A segment has sum if and only if .
Let be the minimum number of operations needed after processing the first characters, where position is the current boundary. If the character at position is a majority character, we may keep it. Before keeping it, we may delete the segment from a previous boundary to position , but only when .
Maintain , the minimum value among previous boundaries with prefix sum . Then each transition can be processed in .
The total time complexity is , and the memory complexity is .