121. 买卖股票的最佳时机

考点

  • 状态机DP

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
const int inf = INT_MAX;
int maxProfit(vector<int>& prices) {
int n = prices.size(), mi = inf, res = 0;
for (int i = 1; i <= n; ++i) {
if (mi != inf && prices[i - 1] > mi)
res = max(res, prices[i - 1] - mi);
mi = min(mi, prices[i - 1]);
}
return res;
}
};

思路

状态机DP的裸题,不解释