小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天结束能够获得的最大利润。
5 1 2 3 4 5Sample 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;
}