#P4597. Transform Sequence to Non-decreasing with Limited Values
Transform Sequence to Non-decreasing with Limited Values
Transform Sequence to Non-decreasing with Limited Values
You are given a sequence of integers. In one operation, you can change any number by adding or subtracting 1 (i.e. the operation is either +1 or -1). Your task is to transform the sequence into a non-decreasing sequence.
Additional Restriction: After all modifications, every number in the resulting sequence must be one of the numbers originally present in the sequence.
Formally, let the original sequence be \(a_1, a_2, \ldots, a_n\) and let \(S\) be the set of distinct numbers that appear in the sequence. You are allowed to change each \(a_i\) to a value \(b_i\) (with a cost of \(|a_i - b_i|\) operations) only if \(b_i \in S\). Moreover, the final sequence \(b_1, b_2, \ldots, b_n\) must satisfy \[ b_1 \le b_2 \le \cdots \le b_n. \] Determine the minimum number of operations required to achieve this transformation.
inputFormat
The first line contains an integer n (\(1 \le n \le 10^5\)), representing the number of elements in the sequence.
The second line contains n space-separated integers \(a_1, a_2, \ldots, a_n\) (each \(|a_i| \le 10^9\)).
outputFormat
Output a single integer: the minimum number of operations needed to convert the sequence into a non-decreasing sequence under the given restrictions.
sample
4
1 3 2 4
1