#P6785. Maximum Sum of Valid Alternating Sequence
Maximum Sum of Valid Alternating Sequence
Maximum Sum of Valid Alternating Sequence
Pigstd has a pile of numbers. He wants to select some of these numbers and arrange them in a sequence \(x_{1}, x_{2}, \dots, x_{p}\) (with \(p\) being the number of chosen numbers) such that the sequence is valid if and only if the following conditions are met:
- \(p \ge 2\).
- Define \(y_{i} = x_{i+1} - x_{i}\) for \(1 \le i \le p-1\) and \(y_{p} = x_{1} - x_{p}\). If you arrange \(y_{1}, y_{2}, \dots, y_{p}\) in order around a circle, every two adjacent numbers in this circle must be opposites, and each of them has absolute value \(k\); that is, \(y_{i} = -y_{i+1}\) (indices taken modulo \(p\)) and \(|y_{i}| = k\) for all \(i\).
It can be observed that such a sequence can only consist of two distinct numbers which alternate. In other words, if we let the two numbers be \(a\) and \(b\), then we must have \(|a - b| = k\) and the sequence is either \(a, b, a, b, \dots\) or \(b, a, b, a, \dots\) (with an even length, at least 2).
You are given an integer \(n\) and a positive integer \(k\), followed by \(n\) integers representing the pile of numbers. Your task is to form a valid sequence by selecting numbers from the pile (each number can be used at most once) so that the sequence is composed of only two distinct values \(a\) and \(b\) satisfying \(|a - b| = k\) and the two values appear an equal number of times. Among all valid sequences, output the maximum possible sum of the numbers in the sequence. If no valid sequence can be formed, output 0.
inputFormat
The first line contains two space-separated integers \(n\) and \(k\) (with \(k > 0\)).
The second line contains \(n\) integers representing the numbers in the pile.
outputFormat
Output a single integer: the maximum sum of the numbers in a valid alternating sequence that can be formed. If no valid sequence exists, output 0.
sample
6 3
1 2 4 7 10 13
23