Max's Mex Med Max Problem

View as PDF

Submit solution


Points: 12
Time limit: 1.0s
Memory limit: 256M

Author:
Problem types

Max has recently been studying various mathematic functions, and he found the Minimum Excluded Value (MEX) function to be quite fun. He also really likes the Median (MED) function, since it also starts with the letter "M". However, Max's absolute favourite math function is the Maximum (MAX) function, because it has the exact same name as him!

The \operatorname{mex} of a set S is the smallest non-negative integer that is not in S. For example, \operatorname{mex}(1, 0, 4, 2) = 3 and \operatorname{mex}(3, 2, 5, 1) = 0.

The \operatorname{med} of a set S is the median of the set. It is found by sorting S in non-decreasing order and taking the element at position \lceil \frac{|S|}{2} \rceil (numbered starting from 1), where |S| denotes the size of the set. For example, \operatorname{med}(1, 0, 4, 2) = 1 and \operatorname{med}(5, 0, 1, 3, 8) = 3.

The \operatorname{max} of a set S is the maximum value in the set. For example, \operatorname{max}(0, -5, 6, 8) = 8 and \operatorname{max}(-3, -5, -2, -9) = -2.

Max also recently learned that a permutation of length N is a sequence of N numbers that contains all the numbers from 0 ... N-1 exactly once. He has decided to come up with his own function on a permutation p_1, p_2,...,p_N.

Define f(x) as the number of pairs (l, r) that satisfy the following:

  • 1 \leq l \leq r \leq N
  • \operatorname{mex}(p_l, p_{l+1},...,p_r)-\operatorname{med}(p_l, p_{l+1},...,p_r) \geq x

Let T denote the set of all integers x \geq 0 such that f(x) \geq K. Max is wondering what is the value of \operatorname{max}(T). Please help him find it!

Constraints

1 \leq N \leq 10^6

1 \leq K \leq 10^{12}

0 \leq p_i \leq N-1

It is guaranteed that p is a permuation of the integers 0 ... N-1.

Input Specification

The first line will contain two space-separated integers N and K.

The second line will contain N space-separated integers p_1, p_2,...,p_N.

Output Specification

If T is not empty, output the value of \operatorname{max}(T). Otherwise, output -1.

Sample Input 1

5 2
0 1 3 2 4

Sample Output 1

3

Explanation for Sample 1

When x = 3, f(3) = 2 which is \geq 2. Below are the following pairs (l, r):

  • (1, 4): \operatorname{mex}(0, 1, 3, 2) - \operatorname{med}(0, 1, 3, 2) = 4 - 1 = 3 \geq 3
  • (1, 5): \operatorname{mex}(0, 1, 3, 2, 4) - \operatorname{med}(0, 1, 3, 2, 4) = 5 - 2 = 3 \geq 3

Sample Input 2

4 5
0 3 1 2

Sample Output 2

-1

Comments


  • 0
    Stonks  commented on May 6, 2026, 10:50 p.m.

    really accurate 12 point difficulty


    • 0
      TheRZ123  commented on May 7, 2026, 12:47 a.m.

      Most testers agreed that the problem difficulty would be around 12p lol