Let the minimum number of operations transform the original array
into an arithmetic progression of the form
Obviously, m[0] \le x \le max(m[0], m[1], ..., m[n - 1]).
We call the sequence
valid if array can be transformed into , i.e., if the condition m[i] \le d[i] holds for all from to n - 1.
It remains to find the smallest value of for which the sequence is valid. This can be done using binary search.
Example
Consider the first test case. Let d = [x, x + 1, x + 2, ..., x + n - 1] be a valid sequence with the minimal possible sum of elements.
Obviously, m[0] = 3 ≤ x ≤ 11 = max(m[i]).
Using binary search, find the smallest value of for which the sequence is valid.
For example, when x = 6, the sequence is not valid, but when x = 8, it is.
Now consider the second test case. Run binary search in the interval 4 \le x \le 7. For example, the sequence is already valid at x = 4.
Algorithm implementation
The input sequence is stored in the array . The sequence x, x + 1, x + 2, ..., x + n - 1 is stored in the array .
#define MAX 1000000
int m[MAX], d[MAX];The function check generates in array a sequence of the form:
If for every i~(0 \le i \le n - 1) the condition m[i] \le d[i] holds, then array can be obtained from array by incrementing some elements by . In this case, the array is considered valid. If the array is valid, the function check returns , otherwise it returns .
int check(int first)
{
for (int i = 0; i < n; i++)
d[i] = first++;
for (int i = 0; i < n; i++)
if (m[i] > d[i]) return 0;
return 1;
}The main part of the program. Read the input value . Compute the maximum value in the array .
scanf("%d", &n);
mx = 0;
for (i = 0; i < n; i++)
{
scanf("%d", &m[i]);
if (m[i] > mx) mx = m[i];
}
start = m[0];
end = mx;Start a binary search for the value in the interval [start; end] = [m[0]; mx].
The goal is to find the smallest value of such that the sequence x, x + 1, x + 2, ..., x + n - 1 can be obtained from the array m[0], m[1], ..., m[n - 1].
while (start < end)
{
mid = (start + end) / 2;
if (check(mid))
end = mid;
else
start = mid + 1;
}Generate the desired arithmetic progression.
for (i = 0; i < n; i++)
d[i] = start++;Compute the minimum number of operations required to obtain this progression.
op = 0;
for (int i = 0; i < n; i++)
op += (d[i] - m[i]);Print the answer.
printf("%lld\n", op);