Description
给定n个数,a[1]到a[n],请你帮忙找出a[i] - a[j]的最大值,其中1 <= i < j <= n
Input
第一行一个数T,表示一共有T组数据(T <= 20); 每组测试数据第一行一个整数n(2 <= n <= 10 ^ 5),表示接下来有n个数,第二行n个整数,不超过10 ^ 6,中间用空格隔开。
Output
每组数据输出一行,表示最大值是多少。
Sample Input 1
2
5
5 2 3 6 1
2
3 2
Sample Output 1
5
1
Source
还是记录一下这个题目吧。
这种化大为小的思路真的太重要了。就像这种题目,我们求a[i]-a[j]的最大值。我们可以一步一步的来。我们把前i个最大的值记录下来,然后让这个最大的值去减,然后再记录差的最大值。这样的话只需要O(n)的时间复杂度。
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int x;
int ans=-1;
cin>>x;
int maxx=x;
for(int i=1;i<n;i++)
{
cin>>x;
ans=max(ans,maxx-x);
maxx=max(maxx,x);
}
cout<<ans<<endl;
}
}
努力加油a啊,(o)/~