Official

G - Longest Y Editorial by en_translator


Let \(A\) be the sequence of indices of Y’s in \(S\) in the increasing order. (For Sample \(1\), \(A=\{1,2,6,8,10\}\).)
Let us define sequence \(B\) by \(B_i = A_i -i\).

Then, the problem can be reworded to as follows.

You may \(+1\) or \(-1\) an element of \(B\) for \(K\) times.
After these operation ended, how many same integers can be there at most? \(\cdots(1)\)

Since the answer has monotonicity, we will use binary search.
Consider the following predicate.

You may \(+1\) or \(-1\) an element of \(B\) for \(K\) times.
After these operation ended, is it possible to obtain \(k\) same integers? \(\cdots(2)\)

In order to solve \((2)\), we feel like considering the following problem.

How many times in total do we need to \(+1\) or \(-1\) in order to make all \(B_i,B_{i+1},\ldots,B_{i+m-1}\) the same integer?

In other words, what we want to know is:

Find the minimum value of the following function. \(\cdots(3)\)
\(\displaystyle f(x) = \sum_{k=i}^{i+m-1} |B_k - x|\)

\((3)\) is a famous problem; \(f(x)\) is minimum at \(x = B_{i+\lfloor \frac{m}{2} \rfloor}\). (If you are not sure why, draw a graph of \(f(x)\).)

Therefore, if we precalculate the cumulative sums, \((3)\) can be found in an \(O(1)\) time.
Hence, denoting \(N=|S|\), \((2)\) can be determined in an \(O(N)\) time, and \((1)\) in a total of \((O \log N)\) time, so the problem has been solved.

posted:
last update: