#P9587. Equalizing Array for Rank Condition
Equalizing Array for Rank Condition
Equalizing Array for Rank Condition
You are given a positive integer n and a positive integer k along with an array a of length n.
For each index i (1 ≤ i ≤ n), define:
\(f(i) = (\text{number of elements of } a \text{ that are greater than } a_i) + 1\),
\(g(i) = \text{number of elements of } a \text{ that are greater than or equal to } a_i\).
In one operation, you can choose an index t (1 ≤ t ≤ n) and increment a[t] by 1.
Your goal is to perform a sequence of operations so that for every index i the following condition holds:
\(f(i) \le k \le g(i)\).
It can be proved that there exists a sequence of operations to achieve this condition.
Note: It turns out that the necessary and sufficient condition to satisfy \(f(i) \le k \le g(i)\) for every index is to make all elements equal. Since you can only increment the elements, the best strategy is to raise every element to the maximum value in the array.
The minimum number of operations required is:
\[ \text{operations} = \sum_{i=1}^{n}(\max(a) - a_i) \]
You are given that 1 ≤ k ≤ n, so once the array is constant the condition 1 ≤ k ≤ n is always satisfied.
inputFormat
The first line contains two integers n and k (1 ≤ n, k ≤ 105 and 1 ≤ k ≤ n).
The second line contains n integers a[1], a[2], …, a[n] (0 ≤ a[i] ≤ 109).
outputFormat
Output a single integer representing the minimum number of operations required to achieve the condition \(f(i) \le k \le g(i)\) for all i.
sample
3 2
3 5 2
5