leetcode 122.Best Time to Buy and Sell Stock II —— 贪心
来源:互联网 发布:反转二叉树 js 编辑:程序博客网 时间:2024/06/14 04:21
拿到题目就觉得应该用dp或者贪心。
dp没找出状态方程,所以用了贪心。
思路:找到左边最小的和右边最大的,相减即为最大值,从头到尾遍历一遍就可以了。
代码:
int maxProfit(vector<int>& prices) { if(prices.empty()) return 0; int l = 0, r = 0; int pf = 0; for(int i = 0; i < prices.size(); ){ l = prices[i]; while(i < prices.size() - 1 && prices[++i] <= l){ l = prices[i]; } r = prices[i]; while(i < prices.size() - 1 && prices[++i] >= r){ r = prices[i]; } pf += r - l; if(r == l) i++; } if(pf <= 0) return 0; return pf; }
这题错了好几遍,因为情况考虑少了,,
望共勉,同进步!
阅读全文
0 0
- leetcode 122.Best Time to Buy and Sell Stock II —— 贪心
- [leetcode][贪心] Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II(贪心)
- leetcode---Best Time to Buy and Sell Stock II---贪心
- LeetCode 122. Best Time to Buy and Sell Stock II
- [Leetcode] 122. Best Time to Buy and Sell Stock II
- [leetcode] 122.Best Time to Buy and Sell Stock II
- 【leetcode】122.Best Time to Buy and Sell Stock II
- 【LeetCode】122.Best Time to Buy and Sell Stock II
- [leetcode] 122. Best Time to Buy and Sell Stock II
- LeetCode #122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II LeetCode
- [LeetCode]122. Best Time to Buy and Sell Stock II
- Leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- LeetCode 122. Best Time to Buy and Sell Stock II
- LeetCode *** 122. Best Time to Buy and Sell Stock II
- leetcode-122. Best Time to Buy and Sell Stock II
- 《机器学习实战》——2.k-近邻算法(KNN )函数总结
- JSP+MVC基础知识
- 蓝桥杯 算法提高 8-1因式分解
- Git详细使用教程
- 语音识别的前端处理
- leetcode 122.Best Time to Buy and Sell Stock II —— 贪心
- Comparable和Comparator 是什么以及区别
- UnityShader初级篇——渐变纹理
- touchpad hid report descrpt windows sample descript
- python_socket网络套接字
- 1079. 延迟的回文数 (20)
- Scala基础学习之函数定义,流程控制,异常处理
- myeclipse2014创建webservice从0开始,跳过一个个的坑
- AutoCAD .Net 遍历符号表