时间轴

2025-10-01

init


题目:

维护两个值即可,一个是当前最低的价格,一个是历史最大利润。每次都假设是今天卖出,然后求今天之前的历史最低点。而这个历史最低点并不需要额外遍历,而是每天考虑的时候顺带记录的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <climits>

class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int max_profit = 0;
int min_price = prices[0];
int i = 0;

for(i = 1; i<n;i++){
max_profit = std::max(max_profit, prices[i] - min_price); // 每次假设第i天卖出股票
min_price = std::min(prices[i], min_price);
}

return max_profit;

}
};