#P1995E2. Let Me Teach You a Lesson (Hard Version)
Let Me Teach You a Lesson (Hard Version)
Description
This is the hard version of a problem. The only difference between an easy and a hard version is the constraints on and . You can make hacks only if both versions of the problem are solved.
Arthur is giving a lesson to his famous knights. Like any other students, they're sitting at the desks in pairs, but out of habit in a circle. The knight is sitting at the desk with the knight .
Each knight has intelligence, which can be measured by an integer. Let's denote the intelligence of the -th knight as . Arthur wants the maximal difference in total intelligence over all pairs of desks to be as small as possible. More formally, he wants to minimize .
However, the Code of Chivalry only allows swapping the opposite knights in the circle, i.e., Arthur can simultaneously perform , for any . Arthur can make any number of such swaps. What is the best result he can achieve?
Each test consists of several test cases. The first line contains a single integer () — the number of test cases. It is followed by descriptions of the test cases.
The first line of each test case contains a single integer () — the number of desks.
The second line consists of integers () — the intelligence values of the knights.
It is guaranteed that the sum of over all test cases does not exceed .
For each test case, output a single line containing one integer — the minimal difference Arthur can achieve.
Input
Each test consists of several test cases. The first line contains a single integer () — the number of test cases. It is followed by descriptions of the test cases.
The first line of each test case contains a single integer () — the number of desks.
The second line consists of integers () — the intelligence values of the knights.
It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, output a single line containing one integer — the minimal difference Arthur can achieve.
Note
In the first test case, Arthur can swap the second and the fourth knights. Then the total intelligence at both desks will be .
In the third test case, Arthur can make operations, which will result in the total intelligence of at each of the desks.
In the fourth test case, Arthur can swap knights with indices and and achieve the difference of . It can be proven that he cannot improve his result any further.