Time to Buy and Sell Stock系列
来源:互联网 发布:专业英语翻译软件 编辑:程序博客网 时间:2024/05/16 07:43
Best Time to Buy and Sell Stock I
给一个数prices[],prices[i]代表股票在第i天的售价,求出只做一次交易(一次买入和卖出)能得到的最大收益。
只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍历即可,在遍历的时间用遍历low记录 prices[o….i] 中的最小值,就是当前为止的最低售价,时间复杂度为 O(n)。
public class Solution { public int maxProfit(int[] prices) { if(prices.length == 0) return 0; int low = prices[0]; int ans = 0; for(int i=1; i<prices.length; i++){ if(prices[i] < low) low = prices[i]; else if(prices[i] - low > ans) ans = prices[i] - low; } return ans; }}
Best Time to Buy and Sell Stock II
贪心算法:
此题和上面一题的不同之处在于不限制交易次数。也是一次遍历即可,只要可以赚就做交易。
public class Solution { public int maxProfit(int[] prices) { if(prices.length == 0) return 0; int ans = 0; for(int i=1; i<prices.length; i++){ if(prices[i] > prices[i-1]) ans += prices[i]-prices[i-1]; } return ans; }}
Best Time to Buy and Sell Stock III
此题是限制在两次交易内,相对要难一些。容易想到的解决办法是,把prices[] 分成两部分prices[0…m] 和 prices[m…length] ,分别计算在这两部分内做交易的做大收益。
class Solution {public: /** * 计算你能获得的最大收益 * * @param prices Prices[i]即第i天的股价 * @return 整型 */ int calculateMax(vector<int> prices) { vector<int> pre(prices.size(),0); vector<int> post(prices.size(), 0); int profix = 0; int low = prices[0]; for (int i = 0; i < prices.size(); i++) { if (prices[i] < low) low = prices[i]; if (profix < prices[i] - low) profix = prices[i] - low; pre[i] = profix; } int hight = prices[prices.size() - 1]; profix = 0; for (int i = prices.size() - 1; i >= 0; i--) { if (prices[i] > hight) hight = prices[i]; if (profix < hight - prices[i]) profix = hight - prices[i]; post[i] = profix; } profix = 0; for (int i = 0; i < prices.size(); i++) { if (profix < pre[i] + post[i]) profix = pre[i] + post[i]; } return profix; }};
阅读全文
0 0
- Time to Buy and Sell Stock系列
- 【Leetcode长征系列】Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock 系列
- LeetCode-Best Time to Buy and Sell Stock系列
- LeetCode Best Time to Buy and Sell Stock 系列
- Bsst Time to Buy and Sell Stock系列
- (java)Best Time to Buy and Sell Stock系列
- Best Time to Buy and Sell Stock 系列问题
- LeetCode Week12: Best Time to Buy and Sell Stock系列
- Best Time to Buy and Sell Stock系列问题题解
- Best Time to Buy and Sell Stock系列问题
- leetCode 系列:best time to buy and sell stock
- LeetCode系列:best time to buy and sell stock
- leetcode 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
- 【IIS】HTTP 错误 500.19
- 云锁机制的网页爬取
- 使用PLSQL完成功能
- 从基础开始学java
- 基本数论(从整除入门到欧拉弃坑到中国剩余BSGS跑路)
- Time to Buy and Sell Stock系列
- swift3 as?和as!
- 判断自己的网络是不是公网IP
- C++内存处理
- JSTL标签
- 初接触SSM(Spring+Spring MVC+Mybatis)
- Java中的设计模式
- [bzoj4034][HAOI2015]树上操作
- 平面射影几何——齐次坐标