open credit system – uva 11078

Problem

Here.

Summary

  • Given a list A, find the max(a[i]-a[j]) with i < j.

Analyse

  • max(a[i]-a[j]) = max(max(a[1..j-1]) - a[j]).
  • Complexity: O(n).

Code in C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <cstring>
#include <cstdio>
using namespace std;
const int INF = 1000000000;
int T;
int n;
int MAX, x, ans;
int () {
cin >> T;
while (T--) {
cin >> n;
cin >> MAX;
ans = -INF;
for (int i = 1; i < n; i++){
cin >> x;
if (MAX - x > ans)
ans = MAX - x;
if (x > MAX)
MAX = x ;
}
cout << ans << endl;
}
return 0;
}