There are nn pieces of cake on a line. The ii-th piece of cake has weight aiai (1≤i≤n1≤i≤n).
The tastiness of the cake is the maximum total weight of two adjacent pieces of cake (i. e., max(a1+a2,a2+a3,…,an−1+an)max(a1+a2,a2+a3,…,an−1+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]a[l,r] of pieces of cake (1≤l≤r≤n1≤l≤r≤n), and reverse it.
The subsegment a[l,r]a[l,r] of the array aa is the sequence al,al+1,…,aral,al+1,…,ar.
If you reverse it, the array will become a1,a2,…,al−2,al−1,ar––,ar−1––––,…–––,al+1––––,al––,ar+1,ar+2,…,an−1,ana1,a2,…,al−2,al−1,ar_,ar−1_,…_,al+1_,al_,ar+1,ar+2,…,an−1,an.
For example, if the weights are initially [5,2,1,4,7,3][5,2,1,4,7,3], you can reverse the subsegment a[2,5]a[2,5], getting [5,7–,4–,1–,2–,3][5,7_,4_,1_,2_,3]. The tastiness of the cake is now 5+7=125+7=12 (while before the operation the tastiness was 4+7=114+7=11).
Find the maximum tastiness of the cake after doing the operation at most once.
Input
The first line contains a single integer tt (1≤t≤501≤t≤50) — the number of test cases.
The first line of each test case contains a single integer nn (2≤n≤10002≤n≤1000) — the number of pieces of cake.
The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — aiai is the weight of the ii-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
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
12
156
160
1998673
2000000000
Code
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
vector<int> numbers(n);
for (int i = 0; i < n; i++) {
cin >> numbers[i];
}
int max1 = -1, max2 = -1;
for (int i = 0; i < n; i++) {
if (numbers[i] > max1) {
max2 = max1;
max1 = numbers[i];
} else if (numbers[i] > max2) {
max2 = numbers[i];
}
}
cout << max1 + max2 << endl;
}
return 0;
}
Conclusion
首先,它从输入中读取一个整数 T,表示有多少组测试数据。
然后,它进入一个循环,每次循环都会处理一组测试数据。在每组测试数据中,它首先读取一个整数 n,表示接下来要处理的数字的数量。
接下来,它创建一个存储整数的列表(或者叫数组),并依次读取这组数字。
然后,它找到这组数字中的最大值和第二大值。也就是说,它找到了最大的两个数字。
最后,它将这两个最大数字相加,并将结果打印出来。整个程序会重复这个过程,直到处理完所有的测试数据为止。它的目标是找到每组数据中的两个最大数字,并将它们的和打印出来。