Maximum Profit
You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.
Write a program which reads values of a currency RtRt at a certain time tt (t=0,1,2,...n−1t=0,1,2,...n−1), and reports the maximum value of Rj−RiRj−Ri where j>ij>i .
Input
The first line contains an integer nn. In the following nn lines, RtRt (t=0,1,2,...n−1t=0,1,2,...n−1) are given in order.
Output
Print the maximum value in a line.
Constraints
- 2≤n≤200,000
- 1≤Rt≤109
Sample Input 1
6 5 3 1 3 4 3
Sample Output 1
3
Sample Input 2
3 4 3 2
Sample Output 2
-1
一开始想到两重循环
for(int j = 1; j < n; ++ j)
for(int i = 0; i < j; ++ i)
maxn = max(maxn , a[j] - a[i]);
但是 n≤200,000 若采用两重循环(O(n^2))会超时, 所以在i自增的过程中, 将现阶段a[i]的最小值(记为minn)保存下来, 此时只需要O(1)便可求出i时刻的最大利益
for(int i = 1; i < n; ++ i)
{
maxn = maxn(a[i] - minn); // minn初始化为a[0]
minn = min(minn, a[i]);
}
注意 maxn的初始值不能是-1, 因为如果序列单调递减, 则最大值有可能小于-1(-1反而比该序列的maxn还大)
方便起见, maxn初值为a[1] - a[0]
边扫描边记录
#include <iostream> #include <algorithm> using namespace std; const int MAX = 200010; int a[MAX]; int main() { int n; cin >> n; for(int i = 0; i < n; ++ i) { cin >> a[i]; } int maxn = a[1] - a[0], minn = a[0]; for(int i = 1; i < n; ++ i) { maxn = max(maxn, a[i] - minn); minn = min(minn, a[i]); } cout << maxn << endl; return 0; }