ALDS1_1_D: Maximum Profit

题解
  1. 暴力解法时间复杂度为O(n^2),n取最大值200000时,会时间超限。
  2. 该解法设立了maxv变量用来记录价格差Rj-Ri (j>i)的最大值,和minv变量记录前i个数据中的最小值。
  3. maxv的初值置为-1000000000,其比价格差可能的最小值-999999999小。minv的初值置为R[0],即以第0个元素驱动循环(在本题中,两个最值maxv和minv不适合都以大值作为初值,minv以循环中的正常值为初值来驱动maxv要更好;当然这里maxv和minv也可以都以循环中正常值R[1]-R[0]和R[0]为初值,但这样其实和都以大值为初值是一样的,都没上一种初始化方法好,原因就在于循环中赋值的先后顺序是maxv在minv前面,所以初始minv要在maxv的前面才能保证每次循环中maxv和minv的值都对应同一次循环)。
  4. 循环从1开始到n-1,每次分别更新maxv和minv的值就行了,maxv的值即为当前元素的值减当前minv的值。
题目
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 Rt at a certain time t (t=0,1,2,...n−1), and reports the maximum value of Rj−Ri where j>i .

Input
The first line contains an integer n. In the following n lines, Rt(t=0,1,2,...n−1) are given in order.

Output
Print the maximum value in a line.

Constraints
2≤n≤200,000
1≤Rt≤10^9

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
代码块
#include <iostream>
#include <algorithm>
using namespace std;

static const int MAX = 200000;//n的最大取值

int main(void)
{
    int i, n, R[MAX];//直接用最大容量作为数组容量,但只对前n个操作
    cin>>n;
    for(i=0; i<n; i++)
        cin>>R[i];
    int maxv = -1000000000;
    int minv = R[0];
    for(i=1; i<n; i++)
    {
        maxv = max(maxv, R[i]-minv);
        minv = min(minv, R[i]);
    }
    cout<<maxv<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值