dp练习题6 股票买卖
2018-01-12 19:02
141 查看
题目:
最近越来越多的人都投身股市,阿福也有点心动了。谨记着“股市有风险,入市需谨慎”,阿福决定先来研究一下简化版的股票买卖问题。假设阿福已经准确预测出了某只股票在未来N天的价格,他希望买卖两次,使得获得的利润最高。为了计算简单起见,利润的计算方式为卖出的价格减去买入的价格。
同一天可以进行多次买卖。但是在第一次买入之后,必须要先卖出,然后才可以第二次买入。
现在,阿福想知道他最多可以获得多少利润。
思路:
这里因为是2次买卖,所以我们可以求出i天前的最大收益和i天后的最大收益,然后求两个加起来的最大值,设lr为i天前的最大收益,lr2为i天后的最大收益,则可得lr[i]=max(lr[i-1],gp[i]-min1),lr2=max(lr[i-1],max1-gp[i]),其中gp代表每天股票的价格,min1代表前i天的最便宜的股票价格,max1代表最贵的股票价格。代码:
#include<cstdio> #include<cstring> int ans,t,n,gp[100001],min1,lr[100001],lr2[100001]; int max(int x,int y) {return x>y?x:y;} int min(int x,int y) {return x<y?x:y;} int main() { scanf("%d",&t); while (t--) { memset(lr,0,sizeof(lr)); memset(lr2,0,sizeof(lr2)); ans=0; scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&gp[i]); min1=gp[1]; for (int i=1;i<=n;i++) { lr[i]=max(lr[i-1],gp[i]-min1); min1=min(gp[i],min1); } min1=gp ; for (int i=n-1;i>=1;i--) { lr2[i]=max(lr2[i-1],min1-gp[i]); min1=max(gp[i],min1); } for (int i=1;i<=n;i++) ans=max(ans,lr[i]+lr2[i]);//求加起来的最大值 printf("%d\n",ans); } }
相关文章推荐
- LeetCode Best Time to Buy and Sell Stock 买卖股票的最佳时机 (DP)
- 简单dp算法——百炼06:股票买卖
- 九度 1537:买卖股票(区间DP)
- 九度OJ 1537 买卖股票(DP)
- 【OpenJudge8464】【序列DP】股票买卖
- OJ4121 and OJ2968-股票买卖 and Maximun sum【各种dp之6 and 9】
- Best Time to Buy and Sell Stock II DP买卖股票
- OpenJudge 百练 2016 ACM 暑期课练习题 股票买卖
- [Leetcode] Best time to buy and sell stock iii 买卖股票的最佳时机
- 如何买卖股票以获得最大收益 java算法
- Leetcode 121 Best Time to Buy and Sell Stock 单次买卖股票最大收益
- 【简单算法】34.买卖股票的最佳时机
- LeetCode 188. Best Time to Buy and Sell Stock IV(股票买卖)
- 最佳买卖股票时间
- Best Time to Buy and Sell Stock 买卖股票最好的时间
- 买卖股票收益最大问题
- poj 3728 lca问题(tarjan+并查集)+dp思路 (树上买卖的最大收益)
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
- LintCode 152 买卖股票的最佳时机 IV
- LeetCode 122. Best Time to Buy and Sell Stock II(股票买卖)