ALDS1_1_D Maximum Profit

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,0002≤n≤200,000
  • 1≤Rt≤1091≤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

分析:用一个变量记录下最小的那个R,另一个变量记录最大的利润,一次扫描。因为这是有时间顺序的!
 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 
 5 int maxProfit(vector<int>& A, int N){
 6   int maxProfit = -2000000000;
 7   int minR = A[0];
 8   for (int i=1;i<N;i++){
 9       maxProfit = max(maxProfit, A[i] - minR);
10       minR = min(minR, A[i]);
11   }
12   return maxProfit;
13 }
14 
15 int main(){
16  int N;
17  cin>>N;
18  vector<int> A(N);
19  for(int i =0; i <N; i++) cin>>A[i];
20 
21  int sw = maxProfit(A,N);
22  cout<<sw<<endl;
23 }

 

posted on 2018-03-08 16:25  vyouman  阅读(162)  评论(0)    收藏  举报