Solution
First, calculate the answer without performing any operation.
It is simply the maximum length of a contiguous segment consisting only of ones.
Now suppose we choose position .
If s_i=0, the operation is allowed only if
If s_i=1, the operation is always allowed.
After choosing , at most three positions can become equal to :
where
and
So first we need to find L_i and R_i for every position.
Finding L_i
Compress all values c_i.
Process positions from left to right and maintain a Fenwick tree.
For every compressed value, the Fenwick tree stores the maximum index of a zero with this value that has already been processed.
For position , query all values strictly smaller than c_i.
The maximum index among them is exactly L_i.
After that, if s_i=0, insert position into the Fenwick tree.
Finding R_i
We do the same thing from right to left.
Now the Fenwick tree stores the minimum index.
For every position , querying all values strictly smaller than c_i gives R_i.
Thus, all values L_i and R_i can be calculated in
Segments around changed positions
For every position , define [lo_x,hi_x] as the maximal segment of ones containing if we change only position to .
If s_x=1, this is simply its current maximal segment of ones.
If s_x=0, we extend from through all consecutive ones immediately to its left and right.
These values can be calculated in time.
Now consider an operation at position .
Take all existing positions among
There are at most three of them.
Sort them:
Each x_j initially corresponds to the segment
Two consecutive changed positions x_j and x_{j+1} belong to the same final segment of ones exactly when there is no unchanged zero strictly between them.
Let pref_i be the number of zeroes among the first positions.
Then there is no zero strictly between x_j and x_{j+1} exactly when
If this condition holds, the corresponding components are merged.
Since there are at most three changed positions, every possible operation can be checked in time.
Correctness
The operation can change only positions , L_i, and R_i.
Therefore, every new segment of ones must contain at least one of these positions.
For every changed position , the interval [lo_x,hi_x] contains exactly all consecutive ones connected to after changing only .
Two such intervals are connected after the operation exactly when there is no unchanged zero between their changed positions.
The prefix sum of zeroes checks exactly this condition.
Therefore, for every possible operation, we correctly calculate every segment of ones that can appear.
Together with the answer obtained without performing an operation, this gives the optimal answer.
Complexity
The two Fenwick tree passes take
time.
All other preprocessing takes time, and every position is checked in .
Therefore, the total complexity is
time and
memory.