leetcode 122. Best Time to Buy and Sell Stock II
来源:互联网 发布:mac上键盘灯不能点亮 编辑:程序博客网 时间:2024/06/05 22:55
题目122. Best Time to Buy and Sell Stock II
标签: 贪心
思路
找到除了第一个点的所有峰值,然后,对于每一个峰值,减去与前一个峰值(包括第一个点,如果它也是峰值的话)之间的山谷值得到差值,将所有的差值加起来就是最大收益
实现
# include <iostream># include <vector>using namespace std;class Solution {public: int maxProfit(vector<int>& prices) { int size = prices.size(); if(size <= 1) return 0; int ret = 0; int last_max = -1, last_min = prices[0]; for(int i = 1; i < size; i++) { if(prices[i] <= last_min && last_max == -1) last_min = prices[i]; else if(prices[i] > last_min && prices[i] >= last_max) last_max = prices[i]; else { // get a valid and best last_min and last_max ret += last_max - last_min; last_min = prices[i]; last_max = -1; } } // the last case if(last_max != -1) ret += last_max - last_min; 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
- 加载大图
- 搭建Node开发环境
- 图片轮播 banner
- 秒杀多线程第九篇 经典线程同步总结 关键段 事件 互斥量 信号量
- pyCharm2017.3版本创建新项目的一些新问题
- leetcode 122. Best Time to Buy and Sell Stock II
- Tensorflow实现多层感知机Multi-layer Preceptron
- Python os.path模块
- Scrapy 通过代理(Proxy)爬取外部网站
- java纯代码获取mac地址
- 代码版动画集合+跳转动画BJ
- 数值计算方法 拉格朗日插值 牛顿插值
- 交易邮件被篡改,18万美元转给黑客
- C和C++中结构体(struct)、联合体(union)、枚举(enum)的区别