[leetcode] 121. Best Time to Buy and Sell Stock
来源:互联网 发布:天使投资 知乎 编辑:程序博客网 时间:2024/06/03 16:47
Question:
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.
Solution:
这个比较简单,记录下当前遇到的最小值,然后如果后面有大于最小值的就尝试卖出看能否赚得更多,遇到更小的值就替换掉最小值。
class Solution {public: int maxProfit(vector<int>& prices) { if (prices.size() == 0) return 0; int ret = 0, min = prices[0]; for (int p : prices) { int diff = p - min; if (diff > ret) ret = diff; if (diff < 0) min = p; } return ret; }};
阅读全文
0 0
- LeetCode 121. Best Time to Buy and Sell Stock
- [Leetcode] 121. Best Time to Buy and Sell Stock
- [leetcode] 121. Best Time to Buy and Sell Stock
- 【leetcode】121. Best Time to Buy and Sell Stock
- [leetcode] 121. Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock LeetCode
- [LeetCode]121. Best Time to Buy and Sell Stock
- Leetcode 121. Best Time to Buy and Sell Stock
- leetcode 121. Best Time to Buy and Sell Stock
- LeetCode 121. Best Time to Buy and Sell Stock
- LeetCode题解:121. Best Time to Buy and Sell Stock
- LeetCode *** 121. Best Time to Buy and Sell Stock
- 【leetcode】121. Best Time to Buy and Sell Stock
- #leetcode#121. Best Time to Buy and Sell Stock
- LeetCode 121. Best Time to Buy and Sell Stock
- 121.[Leetcode]Best Time to Buy and Sell Stock
- leetcode 121. Best Time to Buy and Sell Stock
- Leetcode 121. Best Time to Buy and Sell Stock
- ajax与后台的交互demo
- distinct 排序多字段问题
- Integer比较时用==还是equals
- Dubbo线程模型
- RFID界面设计详解
- [leetcode] 121. Best Time to Buy and Sell Stock
- 程序员过了35岁,感觉自己活成...
- Maven教程完整版免费下载
- 推荐一个免费的SVN版本控制方案
- 【Django】快速掌握常用的正则表达式
- pxe自动化安装配置
- vue中引入jQuery和Bootstrap
- python-day-1
- 25、Android开发基础之Activity之间数据回传(视频+文章)