题目:122. 买卖股票的最佳时机 II
参考题解:买卖股票的最佳时机 II-代码随想录
提交代码因为之前做过leetcode 376 摆动序列,所以很自然想到,使用贪心策略,累加求和所有的上坡(局部谷底->局部峰值)差值。
class Solution {
public:
int maxProfit(vector& prices) {
// 贪心策略:在波动的低估买入,峰值卖出
// 策略证明:不放过每个赚钱的机会
int result = 0;
int low,high;
for(int i=0; i prices[i]){ // 在上坡
low = i;
while(i prices[i]) // 循环退出时,i在当前坡的峰值
i++;
high = i;
result += (prices[high] - prices[low]);
}
}
return result;
}
};
上面的贪心策略,等价于“局部最优:收集每天的正利润,全局最优:求得最大利润”。
下面代码来自参考题解。
class Solution {
public:
int maxProfit(vector& prices) {
int result = 0;
for (int i = 1; i < prices.size(); i++) {
result += max(prices[i] - prices[i - 1], 0);
}
return result;
}
};



