Codeforces Round #735 (Div. 2)-A. Cherry-题解

46 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

@TOC

Codeforces Round #735 (Div. 2)-A. Cherry

传送门 Time Limit: 1 second Memory Limit: 256 megabytes

Problem Description

You are given nn integers a1,a2,,ana_1, a_2, \ldots, a_n. Find the maximum value of max(al,al+1,,ar)min(al,al+1,,ar)max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r) over all pairs (l,r)(l, r) of integers for which 1l<rn1 \le l < r \le n.

Input

The first line contains a single integer tt (1t100001 \le t \le 10\,000) — the number of test cases.

The first line of each test case contains a single integer nn (2n1052 \le n \le 10^5).

The second line of each test case contains nn integers a1,a2,,ana_1, a_2, \ldots, a_n (1ai1061 \le a_i \le 10^6).

It is guaranteed that the sum of nn over all test cases doesn't exceed 31053 \cdot 10^5.

Output

For each test case, print a single integer — the maximum possible value of the product from the statement.

Sample Input

4
3
2 4 3
4
3 2 3 1
2
69 69
6
719313 273225 402638 473783 804745 323328

Sample Onput

12
6
4761
381274500335

Note

Let f(l,r)=max(al,al+1,,ar)min(al,al+1,,ar)f(l, r) = max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r).

In the first test case,

So the maximum is f(2,3)=12f(2, 3) = 12.

In the second test case, the maximum is f(1,2)=f(1,3)=f(2,3)=6f(1, 2) = f(1, 3) = f(2, 3) = 6.


题目大意

给你一个数组,让你从中选取连续的几个数(2\geq2个),计算这些数的最大值和最小值的乘积。

输出最大的那个乘积。

解题思路

假如要选择llrr的数,那么光选择上的复杂度已经达到了O(n2)O(n^2)

接下来看如何优化:

在选择了ll之后(假设a[l]a[l]是这个序列中最大的元素),在llrr之间一定经过a[l+1]a[l+1]。如果a[l+1]a[l+1]很大,那么再往后选就没有意义了,因为a[l+2]a[l+1]a[l+2]\leq a[l+1]。同样,如果a[l+1]a[l+1]很小,再选上a[l+2]a[l+2]也是要经过a[l+1]a[l+1]的,那么最小的那个还是会变成a[l+1]a[l+1]。因此选择长度>2>2的序列没有意义。

因为ll可以任意选择,所以不用担心a[l+2]a[l+2]特别大的情况,因为早晚会选到a[l+2]a[l+2]作为最大的元素(最后一个元素也没有关系,会由倒数第二个与之专门成对)。

代码实现就不困难了。


AC代码

记得用 long longlong\ long

#include <bits/stdc++.h>
using namespace std;
#define mem(a) memset(a, 0, sizeof(a))
#define dbg(x) cout << #x << " = " << x << endl
#define fi(i, l, r) for (int i = l; i < r; i++)
#define cd(a) scanf("%d", &a)
typedef long long ll;
ll a[200010];
int main()
{
    int N;
    cin>>N;
    while(N--)
    {
        int n;
        cd(n);
        for(int i=0;i<n;i++)
            scanf("%lld",&a[i]);
        ll ans=0;
        for(int i=1;i<n;i++)
            ans=max(ans,a[i-1]*a[i]);
        printf("%lld\n",ans);
    }
    return 0;
}

同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:letmefly.blog.csdn.net/article/det…