Best Time to Buy and Sell Stock
2015-11-03 08:42
190 查看
题目:
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
解析:
贪心法,分别找到价格最低和最高的一天,低进高出,注意最低的一天要在最高的一天之前。
把原始价格序列变成差分序列,本题也可以做是最大 m 子段和,m = 1。
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
解析:
贪心法,分别找到价格最低和最高的一天,低进高出,注意最低的一天要在最高的一天之前。
把原始价格序列变成差分序列,本题也可以做是最大 m 子段和,m = 1。
class Solution { public: int maxProfit(vector<int> &prices) { if (prices.size() < 2) return 0; int profit = 0; // 差价,也就是利润 int cur_min = prices[0]; // 当前最小 for (int i = 1; i < prices.size(); i++) { profit = max(profit, prices[i] - cur_min); cur_min = min(cur_min, prices[i]); } return profit; } };
相关文章推荐
- codeforces 592D(树上的思路题)
- 图片抗锯齿问题
- vcl控件常用属性和方法
- 每日一Vim(4)—— 多文件编辑
- HQL和SQL的区别
- Win7/Win8.1设备即将停止销售 2016年10月31日起实施
- jsp小结08 - 9个内置对象01 application
- 创建简单的窗口程序
- 破袭技术壁垒 国产游戏机逆生长与高颜值的往事
- 文章标题
- 关于MKMapView的一些操作小技巧
- css外边距margin重叠及其解决方法
- 众联BreezeCMS实现思路(三)
- C#语言 循环语句
- 宗教信仰
- 把Tomcat和JSP加入 MAC OS X Server
- js 4000 倒计时
- 无法将构造器应用到给定的类型
- [转载] leveldb日知录
- hadoop2.6.0 集群 分布式 安装