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