代码随想录算法训练营第二十七天| 122.买卖股票的最佳时机II 55. 跳跃游戏 45.跳跃游戏II

发布时间 2023-07-08 09:59:49作者: 博二爷

122.买卖股票的最佳时机II 

注意:

1,第一个和最后一个

2,只有一个数的情况

3,2255,这种情况

思路:

1,买入:左:空/高/平  右:高

2,卖出:左:低 右:空/ 低/平

代码:

 1 int maxProfit(vector<int>& prices) {
 2     int result = 0;
 3     if (prices.size() <= 1) return result;
 4     pair<int, int> inOut;
 5     for (int i = 0; i < prices.size(); i++)
 6     {
 7         if (i == 0 && prices[i] < prices[i + 1])
 8         {
 9             inOut.first = prices[i];
10         }
11         else if (i == prices.size() - 1 && prices[i - 1] < prices[i])
12         {
13             inOut.second = prices[i];
14             result += inOut.second - inOut.first;
15         }
16         else if (i > 0 && i < prices.size() - 1 && prices[i] < prices[i + 1] && prices[i] <= prices[i - 1])
17         {
18             inOut.first = prices[i];
19         }
20         else if (i > 0 && i<prices.size() - 1 && prices[i] >= prices[i + 1] && prices[i] > prices[i - 1])
21         {
22             inOut.second = prices[i];
23             result += inOut.second - inOut.first;
24         }
25     }
26 
27     return result;
28 }