D - 1 or 2 Editorial /

Time Limit: 2 sec / Memory Limit: 1024 MB

配点 : 700700

問題文

すぬけ君は黒板と NN 個の飴を持っています。 ii 番目の飴の おいしさaia_i です。

すぬけ君は手持ちの飴がなくなるまで、以下の操作を繰り返します。

  • 手持ちの飴から 11 つ、あるいは 22 つ選んで食べ、その後選んだ飴のおいしさの総和を黒板に書き込む(食べた飴はなくなります)。

すぬけ君は黒板に書かれた値の最大値を XX、最小値を YY として XYX-Y が最小になるようにしたいです。 XYX-Y としてありうる値の最小値を求めてください。

制約

  • 与えられる入力は全て整数
  • 1N50001 \leq N \leq 5000
  • 109ai109-10^{9} \leq a_i \leq 10^9

入力

入力は以下の形式で標準入力から与えられる。

NN
a1a_{1} a2a_{2} \cdots aNa_N

出力

黒板に書かれた値の最大値を XX、最小値を YY とする。 XYX-Y としてありうる値の最小値を出力せよ。


入力例 1Copy

Copy
3
1 2 4

出力例 1Copy

Copy
1
  • 11 回目の操作で美味しさ 1,21,2 の飴を食べ、22 回目の操作で美味しさ 44 の飴を食べるのが最適な操作手順の 11 つです。

入力例 2Copy

Copy
2
-100 -50

出力例 2Copy

Copy
0
  • 11 回目の操作で美味しさ 100,50-100,-50 の飴を食べるのが最適です。

入力例 3Copy

Copy
20
-18 31 -16 12 -44 -5 24 17 -37 -31 46 -24 -2 11 32 16 0 -39 35 38

出力例 3Copy

Copy
13

Score : 700700 points

Problem Statement

Snuke has a blackboard and NN candies. The tastiness of the ii-th candy is aia_i.

He will repeat the operation below until he has no more candy.

  • Choose one or two of his candies and eat them (of course, they disappear). Then, write on the blackboard the total tastiness of the candies he has just chosen.

Snuke wants to minimize XYX-Y, where XX and YY are the largest and smallest values written on the blackboard, respectively. Find the minimum possible value of XYX-Y.

Constraints

  • All values in input are integers.
  • 1N50001 \leq N \leq 5000
  • 109ai109-10^{9} \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

NN
a1a_{1} a2a_{2} \cdots aNa_N

Output

Print the minimum possible value of XYX-Y, where XX and YY are the largest and smallest values written on the blackboard, respectively.


Sample Input 1Copy

Copy
3
1 2 4

Sample Output 1Copy

Copy
1
  • One optimal sequence of operations is to eat the candies with the tastinesses of 11 and 22 in the first operation, and then eat the candies with the tastiness of 44 in the second operation.

Sample Input 2Copy

Copy
2
-100 -50

Sample Output 2Copy

Copy
0
  • It is optimal to eat both candies with the tastiness of 100-100 and 50-50 in the first operation.

Sample Input 3Copy

Copy
20
-18 31 -16 12 -44 -5 24 17 -37 -31 46 -24 -2 11 32 16 0 -39 35 38

Sample Output 3Copy

Copy
13


2025-04-11 (Fri)
09:20:32 +00:00