题目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;
}
};