#C1390. Balanced Parentheses with Minimum Swaps
Balanced Parentheses with Minimum Swaps
Balanced Parentheses with Minimum Swaps
You are given a string p consisting solely of the characters '(' and ')'. Your task is to determine whether it is possible to rearrange p (using only adjacent swaps) to form a balanced parentheses sequence. If it is possible, output YES X where X is the minimum number of adjacent swaps required; otherwise, output NO.
A balanced sequence satisfies the condition that the number of opening parentheses equals the number of closing parentheses, and when traversed from left to right, the running difference satisfies \[ \text{count}('(') - \text{count}(')') \geq 0 \] with equality at the end.
Note: A sequence of odd length or with unequal counts of '(' and ')' cannot be balanced.
inputFormat
The input consists of a single line containing a non-empty string p composed only of the characters '(' and ')'.
outputFormat
If the string can be rearranged into a balanced sequence, print YES X
where X
is the minimum number of adjacent swaps needed. Otherwise, print NO
.
(()
NO