[leetcode]: 121. Best Time to Buy and Sell Stock
来源:互联网 发布:python版本选择 编辑:程序博客网 时间:2024/06/04 00:43
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.
给一段股票价格序列,只能买卖一次,求最大收益
2.分析
第一种:
找到子序列最大的价格差。
遍历价格序列:
持续更新最高价
如果发现最低价可以更新,则最高价,最低价同时更新,差值也更新。
int maxProfit(vector<int>& prices) { if(prices.size()==0) return 0; int low = prices[0]; int high = prices[0]; int maxP = -1; for (int i = 1; i < prices.size(); i++) { if (prices[i] > high) high = prices[i]; if(prices[i]<low){ maxP = maxP > (high - low) ? maxP : high - low; low = prices[i]; high = prices[i]; } } maxP = maxP > (high - low) ? maxP : high - low; return maxP;}
第二种:
看solution的解答提到了Kadane’s Algorithm。
提到了这样一种情况,如果给的不是价格序列,而是价格差序列怎么做?这个问题就转化为求连续子序列的最大和。
例如,
股票价格为{1, 7, 4, 11},判断为1买入,11卖出,profile=10
价格差序列{0, 6, -3, 7},判断为6-3+7=10,最大profile=10
int maxProfit(vector<int>& prices) { if(prices.size()==0) return 0; int max_cur = 0; int max_sofar = 0; for (int i = 1; i < prices.size(); i++) { max_cur = max(0, max_cur + prices[i] - prices[i - 1]); max_sofar = max_sofar > max_cur ? max_sofar : max_cur; } return max_sofar;}
阅读全文
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
- IOS学习路上的各种疑难杂症(不断更新ing)
- 机器学习规则:ML工程最佳实践----rule_of_ml section 3【翻译】
- 字符串方法的扩展
- Java Timer和TimerTask详解
- 欢迎使用CSDN-markdown编辑器
- [leetcode]: 121. Best Time to Buy and Sell Stock
- 仿天猫网站开发笔记4:将Django模板变量传递给外部js调用的方案
- gnu-c 对浮点型数据除0.0的处理
- c++关于结构体动态链表初始化添加删除操作代码
- SpringMVC使用了@ResponseBody报406错误的问题
- Machine Learning Class 1:Introduction,supervised & unsupervised learning
- PC端微信缓存清理方法
- vim C/C++常用配置
- 小知识-绊倒大部分人-持续更新