Common Remainder: Removing a Segment#545

Solution

Two numbers have the same remainder modulo if and only if their difference is divisible by . Thus, for a fixed sequence, the largest suitable is the greatest common divisor of consecutive differences. Every other pairwise difference is also divisible by this gcd because it is a sum of consecutive differences.

Let a_i=x_{i+1}-x_i for 1 \le i < n. Build two arrays:

Consider removing elements from through r=l+k-1. The consecutive differences in the remaining sequence consist of three parts:

Ignore any missing parts. Start the gcd calculation at zero, using the fact that the gcd of zero and a positive integer is that integer.

Try all n-k+1 values of . For each, find the gcd of the listed values and take the largest result. The new difference between the two parts is computed directly from two sequence elements.

Correctness proof

For each removal, the algorithm considers every consecutive difference in the remaining sequence: unchanged differences on the left and right, and the difference joining the two parts when both are non-empty. There are no other consecutive pairs after the removal.

The gcd of these differences divides every pairwise difference, so all remaining numbers have the same remainder modulo this gcd. Conversely, any suitable must divide every consecutive difference and therefore cannot exceed their gcd.

Thus, the algorithm finds the largest suitable for each removal. Since it tries every allowed removal, the largest result is the required answer.

Complexity

The time complexity is O(n \log c), where c \le 2 \cdot 10^9 is the largest possible difference between two input numbers. The extra space is .