Editorial for Max's Mex Med Max Problem
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Observations
For simplicity, let's denote as the subarray
.
Observe that is monotonic, that is
. The proof is not difficult to see, as any valid pair
that satisfies
will also satisfy
, therefore
will always be at least
.
From this, we can binary search the maximum such that
. The rest of the editorial will explain computing
for
. We do not need to consider when
because
(the
of a subarray will never equal to the
).
Computing 
We can iterate an integer from
and count the number of pairs
such that
and
.
Let be the index of the value
in the permutation
,
, and
. This means that
is the smallest subarray that contains all the integers
. There are two restrictions that must be satisfied for a pair
to have a
.
- The subarray must contain all integers from
to
. This means that
and
.
- The subarray must not contain
, meaning that either
or
.
Next, , which can be rewritten as
. Notice that if the subarray contains all integers
, then there are exactly
integers in the subarray that are
(assuming
). This means that the subarray can include at most
extra integers to make the median
. Therefore, the subarray can have a length of at most
, meaning that a pair
must satisfy
.
Now let's see how we can use the above restrictions to count the number of pairs for each . There are two cases we need to consider:
Case 1:
can be chosen from the range
and
must satisfy
and
. We can iterate every
from
and add
to the number of pairs.
Case 2:
can be chosen from the range
and
must satisfy
and
. We can iterate every
from
and add
to the number of pairs.
Note that when , although
does not exist in the permutation, we can let
and still run the above algorithm.
Time Complexity:
While there are nested loops (iterating or
inside the
loop), notice that
strictly decreases and
strictly increases as
grows. We only iterate over new indices, meaning that no index is visited more than once across the entire execution of
. Thus,
runs in amortized
time.
Final Solution
The final solution consists of binary searching for the largest in the range
such that
. If no such
exists, then the answer is
.
can be computed in
, so the final time complexity of the solution is
.
Bonus: Try to find a way to count the number of pairs for each in
without iterating
or
.
Comments