World T20 X Team (full version)

MEDIUM · C · 2000ms

This is the real deal: for the actual World T20 tournament, Zayan must answer many queries, each asking for a team of size X that maximizes the total pairwise rating gap, and needs every query answered instantly. Given N player ratings, answer Q queries. Each query gives X (team size). For that X, choose X players to MAXIMIZE the sum of |rating_i - rating_j| over all pairs in the chosen team. Print the answer for each query. Precompute using sorted prefix sums so each query answers in O(1) or O(log N).

Input

Line1: N. Line2: N integers. Line3: Q. Next Q lines: X.

Output

Q lines: maximum sum for each X.

Constraints

1 ≤ N,Q ≤ 10^5

Sample Input

5
1 2 3 4 5
2
2
4

Sample Output

4
10
main.c
Loading editor…

Write C, then Run (custom I/O) or Submit (sample tests). ⌘/Ctrl+Enter submits.

World T20 X Team (full version) · DIU ContestHub