uva11078 Open Credit System

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2019

题目大意:

  给一个长度为n的序列,求Ai - Aj (i < j)的最大值。序列的长度最大是10^5

题目思路:

  动态维护某一个数字之前的最大值,不断更新之。同时不断更新结果ans,更新的方法是ans和当前数字之前的最大值与这个数字作差,取其中的最大值。时间复杂度O(N),空间复杂度O(1)

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstdlib>
 5 #include <cstring>
 6 #include <cmath>
 7 using namespace std;
 8 void solve() {
 9   int t; scanf("%d", &t);
10   while (t--) {
11     int n; scanf("%d", &n);
12     int a, b; scanf("%d%d", &a, &b);
13     int i, Max = max(a,b), ans = a - b;
14     for (i = 0; i < n - 2; ++i) {
15       scanf("%d", &b);
16       ans = max(ans, Max - b);
17       Max = max(Max, b);
18     }
19     printf("%d\n", ans);
20   }
21 }
22 int main(void) {
23   //freopen("11078.in", "r", stdin);
24   solve();
25   return 0;
26 }

这个想法很神奇~

也可以用数组先把序列保存起来。

posted on 2013-05-21 18:26  aries__liu  阅读(328)  评论(0编辑  收藏  举报