7-6 拿糖果 (15 分)
Long long ago,a handsome boy whose name is HSP studied in JSU of information science and engineering. He is clever and always thinks of ways to make fun of others. Now,it is your turn.
HSP和他的女朋友ZM来到了商店,商店有n个糖果,标号依次为1,2,3…n,对应的价值为W1,W2,W3…Wn。现在HSP先拿走一个标号为a的糖果,标号小于a的糖果就被ZM收回去了,然后HSP只能在剩下的糖果中选一个标号为b的糖果,请问Wa-Wb的最大值是多少?
输入格式:
多组数据输入,每一组数据第一行输入一个数字 n(2<=n<=100000),接下来n行,每行输入一个wi表示第i个糖果的价值
(0<wi<=100000)
输出格式:
每组数据输出Wa-Wb的最大值
输入样例:
3
3 2 1
6
1 1 1 1 1 1
输出样例:
2
0
如果从前往后进行会超时,换为从后向前进行就好了,还有一点要注意,最大值可能为负。
#include <iostream>
#include <vector>
#include <cstdio>
#include <cmath>
using namespace std;
int main()
{
int n;
while (scanf("%d",&n)!=EOF)
{
// vector<int>a;
int a[100010]={0};
int i,j;
for(i=0;i<n;i++)
{
// int t;
// scanf("%d",&t);
// a.push_back(t);
cin>>a[i];
}
int max=-1111111111,t=0;
// for(i=0;i<n-1;i++)
// {
// for(j=i+1;j<n;j++)
// {
// t=a[i]-a[j];
// if(t>max)
// {
// max=t;
// }
// }
// }
t=a[n-1];
for(i=n-2;i>=0;i--)
{
if(max<a[i]-t)
{
max=a[i]-t;
}
if(t>a[i])
{
t=a[i];
}
}
printf("%d\n",max);
// a.clear();
}
return 0;
}