class Solution {
public:
int maxProfit(vector<int>& prices) {
int i = 0;
int valley = -1;
int peak = -1;
int max_profit = 0;
while (i < prices.size() - 1)
{
// find valley
while (i < prices.size() - 1 && prices[i] >= prices[i + 1])
{
i++;
}
valley = i;
// find peak
while (i<prices.size() - 1 && prices[i] <= prices[i + 1])
{
i++;
}
peak = i;
max_profit += prices[peak] - prices[valley];
}
return max_profit;
}
};
LeetCode122. 买卖股票的最佳时机 II
最新推荐文章于 2024-08-13 20:54:49 发布