122. Best Time to Buy and Sell Stock II的C++解法
来源:互联网 发布:spark教程python版本 编辑:程序博客网 时间:2024/05/24 00:04
题目说得不是特别清楚,研究了好几遍,意思其实就是只有一支股票,卖了之后才能再买进,买了之后才能再卖出。但是不限制交易次数。
看起来特别复杂其实用贪心就可以解决。对于每一笔交易 假设是从i天买入 j天卖出 ,如果有j+1天的价格高于j天,所以肯定是从i到j+1利润更高,同样的如果有第i-1天价格比第i天更低,肯定是从i-1天到j天利润更高。画个曲线图更容易理解,只要在低谷买入,高峰卖出,收益就是最大的。
转换成代码就更简单了,只要后一天比前一天价格高,就算收益。
int maxProfit(vector<int> &prices) { int ret = 0; for (size_t p = 1; p < prices.size(); ++p) ret += max(prices[p] - prices[p - 1], 0); return ret;}
0 0
- 122. Best Time to Buy and Sell Stock II的C++解法
- 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] 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】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
- 122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- 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 122. Best Time to Buy and Sell Stock II
- nyoj1277 Decimal integer conversion (河南省acm第九届省赛)
- (贪心)折线分割平面
- docker
- SQL中定义主键的方法
- WEBRTC视频网络传输到解码输出
- 122. Best Time to Buy and Sell Stock II的C++解法
- AndroidStudio下设置自动注释作者和一些预设信息
- jsp--对象感知监听器
- c#——web service异构系统调用
- shell alias 别名
- CodeForces 641 A.Little Artem and Grasshopper(水~)
- Android App包瘦身优化实践
- 文章标题
- python获取交互式ssh shell