Official

C - Peak Editorial by en_translator


The problem statement has an unfamiliar term “half-open interval,” so let us review the situation by describing the problem statement in detail. We discuss the following two cases.
Notice that a gift is always placed at an integer coordinate.

  • If the chosen real value \(x\) is an integer
    • You can acquire the gifts at coordinates \(x,x+1,\dots,x+M-1\). Note that you cannot claim the gift at coordinate \(x+M\).
  • If the chosen real value \(x\) is not an integer
    • Let \(\lceil x \rceil\) be the integer obtained by rounding up \(x\). Then, you can acquire the gifts at coordinates \(\lceil x \rceil, \lceil x \rceil+1,\dots,\lceil x \rceil+M-1\).

In any case, you end up choosing \(M\) contiguous integer coordinates, and acquiring all the gifts placed there.

Thus, it is sufficient to sort \(A_i\) beforehand, enumerate the gift with the smallest coordinate, and find the gift with the largest coordinate that you can acquire.
This can be solved in a total of \(O(N)\) or \(O(N \log N)\) time with a sliding window or a binary search. (Note that an additional complexity of \(O(N \log N)\) is required by the sort.)

Sample code (Python):

n,m = map(int,input().split())
a = list(map(int,input().split()))

a.sort()
a.append(9000000000000)

res = 0
r = 0
for l in range(0,n):
    while a[r] < a[l]+m:
        r += 1
    res = max(res,r-l)

print(res)

posted:
last update: