Leetcode 122. Best Time to Buy and Sell Stock II
来源:互联网 发布:淘宝外贸的衣服能买吗 编辑:程序博客网 时间:2024/06/05 21:54
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
easy的题以前是不写的,因为现在研二,一年后要找工作了感觉还是要写一写,发现真是怎么瞎几把写都能AC。。。。
策略:l是当前最小的,r保证了能最大,并且l到r是上升 那么ans += prices[r] - prices[l] l = r+1
简单举个例子 没有严格证明:
i <j < k < l , k=j+1, ak > ai
ai < aj > ak < al
ai 到aj就符合上面的i 到j是上升的,两种策略:
(1)按照上面的策略,ans = aj - ai + al - ak = aj - ak - (al - ai)
(2)不按照上面的策略,取ai到ak, ans = al - ak + ak - ai = al - ai
因为aj > ak 所以第一个的ans更大。
上面的例子略有问题的是 ak用了两次。 增加的话就是多个ak+1 其实证明思路同上。
class Solution {public: int maxProfit(vector<int>& prices) { if (prices.size() <= 1) return 0; prices.push_back(-1); int ret = 0, l = 0, r = 1; for (int i = 1; i < prices.size(); i++) { if (prices[i] < prices[i-1]) { ret += prices[i-1] - prices[l]; l = i; } } return ret; }};
阅读全文
0 0
- 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
- 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
- 【清华集训2017模拟】Create
- Codeforces 785B Anton and Classes(贪心)
- bootstrap angularjs 实现jsp页面购物车
- 剑指Offer—28—数组中出现次数超过一半的数字
- 润乾报表如何配置/部署多个lmd文件
- Leetcode 122. Best Time to Buy and Sell Stock II
- html 学习 第一天
- USB驱动--概念
- LintCode_二叉查找树迭代器
- Vue列表过渡
- C++实验二 控制结构和函数 打印温度柱状图 2.2 处理零下温度
- JAVA学习50_java 主类的main方法调用其他方法
- php正则
- 20170823-BIN