UVa 11549 Open Credit System

本博客介绍了一个算法,用于从一组整数中找到两个数的最大差值,并在此过程中维护当前最大值。通过从小到大枚举并更新最大值,实现高效计算。

题意:给出n个数,找出两个整数a[i],a[j](i < j),使得a[i] - a[j]尽量大

从小到大枚举j,在这个过程中维护a[i]的最大值

maxai晚于ans更新,

可以看这个例子

 1 8 9 10 11

正确的应该是-1

如果更早更新的话,算出来就是0

用数组来存的

 1 #include<iostream>  
 2 #include<cstdio>  
 3 #include<cstring> 
 4 #include <cmath> 
 5 #include<stack>
 6 #include<vector>
 7 #include<map> 
 8 #include<set>
 9 #include<queue> 
10 #include<algorithm>  
11 using namespace std;
12 
13 typedef long long LL;
14 const int INF = (1<<30)-1;
15 const int mod=1000000007;
16 const int maxn=1000005;
17 
18 int a[maxn];
19 int n;
20 
21 int main(){
22     int T;
23     scanf("%d",&T);
24     while(T--){
25         scanf("%d",&n);
26         for(int i = 0;i < n;i++) scanf("%d",&a[i]);
27         int ans = a[0] - a[1];
28         int maxai = a[0];
29         for(int j = 1;j < n;j++){
30             ans = max(ans,maxai - a[j]);
31             maxai = max(maxai,a[j]);
32         //    printf("j = %d  maxai = %d  ans = %d\n",j,maxai,ans);
33         }
34         printf("%d\n",ans);
35     }
36     return 0;
37 }
View Code

边读边算的

 1 #include<iostream>  
 2 #include<cstdio>  
 3 #include<cstring> 
 4 #include <cmath> 
 5 #include<stack>
 6 #include<vector>
 7 #include<map> 
 8 #include<set>
 9 #include<queue> 
10 #include<algorithm>  
11 using namespace std;
12 
13 typedef long long LL;
14 const int INF = (1<<30)-1;
15 const int mod=1000000007;
16 const int maxn=1000005;
17 
18 int main(){
19     int T;
20     scanf("%d",&T);
21     while(T--){
22         int n;
23         scanf("%d",&n);
24 
25         int x,y,ans;
26         scanf("%d %d",&x,&y);
27         ans = x-y;
28         int maxai = x;
29         for(int i = 2;i<n;i++){
30             scanf("%d",&x);
31             ans = max(ans,maxai - x);
32             maxai = max(maxai,x);
33         }
34         printf("%d\n",ans);
35     }
36     return 0;
37 }
View Code

 

转载于:https://www.cnblogs.com/wuyuewoniu/p/4626761.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值