L - 股票价格II

小Hi最近在关注股票,为了计算股票可能的盈利,他获取了一只股票最近N天的价格A1~AN

在小Hi的策略中,每天可以在下列三种操作中选取一种:

1.什么也不做;

2.按照当天的价格买进一个单位的股票;

3.按照当天的价格卖出部分或所有股票。

现在小Hi希望能够知道,如果在N天前手中持有的股票数为0,并且假设拥有无限的金钱,在这N天结束能够获得的最大利润是多少?

Input

第一行包含一个整数N。  

第二行包含N个整数,A1, A2, ... AN。  

对于30%的数据, 1 ≤ N ≤ 103  

对于100%的数据,1 ≤ N ≤ 106, 1 ≤ Ai ≤ 100

Output

输出这N天结束能够获得的最大利润。

Sample Input
5
1 2 3 4 5
Sample Output
10

这题我刚开始一直在往正面去想,采用每此从一个未处理的区间里找出最大值,然后从st到ed进行利润的计算,可是超时,所以就用了前缀数组,简化区间利润的计算,可还是超时,问了队友才知道要从后往前考虑,用now变量维护当前股票的最大值,这样就优化很多,不会超时



/*#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf = 1e6 + 10;
ll th[inf];
ll qian[inf];
int main()
{
    int n;
    ll tot = 0;
    scanf("%d", &n);
    ll Max = 0;
    int ed = 0,st = 0;
    for(int i = 0; i < n; i ++){
        scanf("%lld", &th[i]);
        if(i) qian[i] = qian[i - 1] + th[i];
        else qian[i] = th[i];
        if(Max < th[i]){
            Max = th[i];
            ed = i;
        }
    }
    while(true){
        if(ed > 0 && ed > st && st > 0)
            tot += th[ed] * (ed - st) - (qian[ed - 1] - qian[st - 1]);
        else  if(ed > 0 && ed > st && st == 0) tot += th[ed] * (ed - st) - (qian[ed - 1]);
        Max = 0;
        st = ed + 1;
        for(int i = st; i < n; i ++){
            if(Max < th[i]){
                Max = th[i];
                ed = i;
            }
        }
        if(st >= n) break;
    }
    cout << tot << endl;
    return 0;
}

*/

上面是超时代码

--------------------------------------------------------------------------------------------------

#include <bits/stdc++.h>
using namespace std;
const int inf = 1e6 + 10;
int th[inf];
int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i ++){
        scanf("%d", &th[i]);
    }
    int now = th[n - 1];
    int tot = 0;
    for(int i = n-2; i >= 0 ; i --){
        if(now >= th[i]){
            tot += now - th[i];
        }else now = th[i];
    }
    cout << tot << endl;
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值