[LeedCode OJ]#121 Best Time to Buy and Sell Stock
来源:互联网 发布:火花棱镜淘宝 编辑:程序博客网 时间:2024/04/30 22:32
【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱:libin493073668@sina.com】
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
题意:
有一个数组,第i个数表示第i天股票的价格,我们可以在第i天买进或者卖出,现在只能进行一次买,一次卖,问能得到的最大收益是多少
思路:
dp[i][j]表示到第i天里股票的最大值与最小值,j=0表示最小值,j=1表示最小值,要注意的是最小值不能在最大值的右边
class Solution{public: int maxProfit(vector<int>& prices) { if(prices.size()==0) return 0; int len = prices.size(),i,j,k; int (*dp)[2] = new int [len+1][2]; dp[0][0] = prices[0]; dp[0][1] = prices[1]; int ans = 0; for(i = 1; i<len; i++) { if(prices[i]<dp[i-1][0]) { dp[i][0] = prices[i]; dp[i][1] = prices[i]; continue; } dp[i][0] = dp[i-1][0]; dp[i][1] = max(dp[i-1][1],prices[i]); ans = max(ans,dp[i][1]-dp[i][0]); } return ans; }};
0 0
- [LeedCode OJ]#121 Best Time to Buy and Sell Stock
- 【leedcode】122. Best Time to Buy and Sell Stock II
- 【LeedCode】121.Best Time to Buy and Sell Stock
- 【leedcode】121. Best Time to Buy and Sell Stock
- LeetCode OJ 121 Best Time to Buy and Sell Stock
- LeetCode OJ:Best Time to Buy and Sell Stock
- LeetCode OJ:Best Time to Buy and Sell Stock II
- LeetCode OJ:Best Time to Buy and Sell Stock III
- LeetCode OJ - Best Time to Buy and Sell Stock
- LeetCode OJ - Best Time to Buy and Sell Stock II
- LeetCode OJ - Best Time to Buy and Sell Stock III
- [LeetCode OJ]Best Time to Buy and Sell Stock
- [LeetCode OJ]Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- BW系列基础
- C# XML与Json之间相互转换实例详解
- 励精图治---Concurrency---如何创建多线程
- CocoaPods pod install/pod update更新慢
- hdu 素数环1016
- [LeedCode OJ]#121 Best Time to Buy and Sell Stock
- 离屏Canvas——制作放大镜效果
- package 和 import 关键字
- android sdk 镜象站点
- Spring MVC之@RequestMapping 详解
- 1.实例变量可见度2.方法3.setter, getter
- android studio中图片格式的问题
- 关于C语言中二维数组的P+1与*(P+1)个人浅见
- Spring Security Remember Me Example