当 fast 价格比 slow 价格高,更新最大利润,fast++;当 fast 比 slow 价格低,跟新slow到fast位置,fast++;最后返回最大利润max_profit。
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() < 2)
return 0;
int slow = 0;
int fast = 1;
int max_profit = 0;
while (fast < prices.size()) {
if (prices[fast] > prices[slow]) {
max_profit = max(prices[fast++] - prices[slow], max_profit);
} else {
slow = fast++;
}
}
return max_profit;
}
};
跟上一道题不一样的是,要将fast价格和fast-1价格相比较,而不是和slow相比较,因为一旦有价格降低的情况出现,就应该进行新一轮的买卖。
当 fast 价格比 fast-1 价格高,继续持有股票,更新最大利润max_profit,fast++;当 fast 比 fast-1 价格低,说明要卖了再买,更新slow到fast位置,累加总利润sum_profit,最大利润置为0,fast++;循环结束后再累加一次总利润并返回sum_profit。
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() < 2)
return 0;
int slow = 0;
int fast = 1;
int max_profit = 0;
int sum_profit = 0;
while (fast < prices.size()) {
if (prices[fast] > prices[fast - 1]) {
max_profit = max(prices[fast] - prices[slow], max_profit);
} else if (prices[fast] < prices[fast - 1]) {
slow = fast;
sum_profit += max_profit;
max_profit = 0;
}
fast++;
}
sum_profit += max_profit;
return sum_profit;
}
};