Editorial for COCI '12 Contest 4 #4 Razlika
Submitting an official solution before solving the problem yourself is a bannable offence.
For the sake of simplicity, let us determine
Notice that there is always an optimal solution in which we choose
Proof
Let
If there does not exist an unchosen number
in the sorted array from the interval , a subsequence of consecutive elements is chosen and the proof is finished.Else, determine which number out of
and has the greater distance to the set of chosen numbers. We remove it, and pick instead. The greatest absolute difference is now decreased because (or ) is less than . By removing a number we have not increased the smallest absolute difference because we have removed the greater of the two differences (distances). By adding , the difference of its two chosen neighbours in a sorted array is divided in two parts, so is not increased this way. We have thus proved that each optimal solution can be reduced to the consecutive subsequence in a sorted array.
Here is a simple solution with a time complexity of
Notice that the greatest difference is actually the difference between the first and the last element of the substring and we can calculate it in a constant time complexity for each substring. If we keep the last
Notice that the elements of the array are limited to the interval of
Let us take a look at the data structure we use to keep the differences of consecutive elements of the array. If the newly inserted difference is smaller than another difference in the structure, the other one will never be the smallest because it will be deleted before the newly inserted one. Therefore, the differences can be kept in a monotonous deque with two ends. The smallest difference in the substring will be the one at the beginning of the deque. Since
Comments