Editorial
First imagine changing every character to ). Let be the cost of flipping all positions that were originally (.
If position is then chosen to become (, the additional cost is when the original character was (, and otherwise. A correct parenthesis string must contain at least opening parentheses in the odd prefixes of lengths .
Scan from left to right and put each available additional cost into a priority queue. Whenever an odd position is reached, choose the cheapest not-yet-chosen position among the prefix and make it an opening parenthesis. Each step satisfies the newly increased prefix requirement as cheaply as possible.
The priority queue gives an algorithm. Solution written by GPT5.6