A special site for solving fun programming problems and challenges, interested in computer science, programming, basics, data structure and algorithms

 A. Maximum Cake Tastiness

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output




There are n pieces of cake on a line. The i-th piece of cake has weight ai (1in).

The tastiness of the cake is the maximum total weight of two adjacent pieces of cake (i. e., max(a1+a2,a2+a3,,an1+an)).

You want to maximize the tastiness of the cake. You are allowed to do the following operation at most once (doing more operations would ruin the cake):

  • Choose a contiguous subsegment a[l,r] of pieces of cake (1lrn), and reverse it.

The subsegment a[l,r] of the array a is the sequence al,al+1,,ar.

If you reverse it, the array will become a1,a2,,al2,al1,ar_,ar1_,_,al+1_,al_,ar+1,ar+2,,an1,an.

For example, if the weights are initially [5,2,1,4,7,3], you can reverse the subsegment a[2,5], getting [5,7_,4_,1_,2_,3]. The tastiness of the cake is now 5+7=12 (while before the operation the tastiness was 4+7=11).

Find the maximum tastiness of the cake after doing the operation at most once.

Input

The first line contains a single integer t (1t50) — the number of test cases.

The first line of each test case contains a single integer n (2n1000) — the number of pieces of cake.

The second line of each test case contains n integers a1,a2,,an (1ai109) — ai is the weight of the i-th piece of cake.

Output

For each test case, print a single integer: the maximum tastiness of the cake after doing the operation at most once.

Example
input
Copy
5
6
5 2 1 4 7 3
3
32 78 78
3
69 54 91
8
999021 999021 999021 999021 999652 999021 999021 999021
2
1000000000 1000000000
output
Copy
12
156
160
1998673
2000000000
Note

In the first test case, after reversing the subsegment a[2,5], you get a cake with weights [5,7_,4_,1_,2_,3]. The tastiness of the cake is now max(5+7,7+4,4+1,1+2,2+3)=12. This is the maximum possible tastiness of the cake one can obtain by performing the operation at most once.

In the second test case, it's optimal not to do any operation. The tastiness is 78+78=156.

In the third test case, after reversing the subsegment a[1,2], you get a cake with weights [54_,69_,91]. The tastiness of the cake is now max(54+69,69+91)=160. There is no way to make the tastiness of the cake greater than 160 by performing at most one operation.


solution:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{

   int t;
   cin >> t;
   for (int j = 0; j < t; j++)
   {
	   int n;
	   cin >> n;
	   vector<int> v(n);
	   for (int i = 0; i < n; i++)  cin >> v[i];
	   sort(v.begin(), v.end(), greater<int>());
	   int max;
	   max = v[0] + v[1];
	   cout << max << "\n";
   }

	return 0;
}

No comments:

Post a Comment