一串数字根据大小看成高低起伏的序列。用后面的峰值减去前面的谷值可以得到最大差值。
int Solution::maxProfit(vector<int>& prices)
{
if(prices.size() < 2)
return 0;
int min_index = 0, max_index = 0;
int min = prices[0];
int res = 0;
while(min_index < prices.size() && max_index < prices.size())
{
// 找到新的谷值
min_index = max_index;
while(min_index + 1 < prices.size() && prices[min_index] >= prices[min_index + 1])
min_index++;
// 和旧谷值比较,记录小的那个
min = min(min, prices[min_index]);
// 找到新谷值后面的峰值
max_index = min_index + 1;
while(max_index + 1 < prices.size() && prices[max_index] <= prices[max_index + 1])
max_index++;
//峰值 - 最小谷值 = 最大差值
if(max_index < prices.size())
res = max(res, prices[max_index] - min);
}
return res;
}