#P9842. Klee's Mode Maximization
Klee's Mode Maximization
Klee's Mode Maximization
In the city of Monstadt, Klee is given an integer sequence \(a_1, a_2, \ldots, a_n\) and an integer \(k\). You are allowed to perform the following operation at most once:
Select two indices \(l\) and \(r\) (\(1 \le l \le r \le n\)) and add \(k\) to every element \(a_i\) for \(l \le i \le r\). It is also allowed to not perform any operation.
After the operation, the mode of the sequence is defined as the number with the maximum frequency. In other words, for a candidate number \(x\), the final frequency can be computed as follows:
[ \text{final frequency} = \text{(number of indices } i \text{ with } a_i = x \text{ and not operated)} + \text{(number of indices } i \text{ with } a_i = x - k \text{ in the operated segment)}. ]
If we denote \(\text{cnt}(x)\) as the frequency of \(x\) in the original array, and if we choose a contiguous segment \([l,r]\) for the operation, then the net change in the frequency for candidate \(x\) is:
[ \text{gain} = #{i\in[l, r] : a_i = x-k} - #{i\in[l, r] : a_i = x}. ]
You may choose the segment optimally (or choose not to perform any operation at all). The answer is the maximum possible final frequency of any candidate number \(x\):
[ \max_{x}\Big(\text{cnt}(x) + \max\big(0, \max_{[l,r]}\big(#{i\in[l, r] : a_i = x-k} - #{i\in[l, r] : a_i = x}\big)\big)\Big). ]
</p>Your task is to compute this maximum mode frequency.
inputFormat
The first line contains two integers (n) and (k). The second line contains (n) integers (a_1, a_2, \ldots, a_n).
outputFormat
Output a single integer — the maximum frequency of the mode number after applying the operation optimally.
sample
5 3
1 1 4 1 4
4