跳到主要内容

121 买卖股票的最佳时机

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn8fsh/

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/

cost: 4m23s

class Solution {
public:
int maxProfit(vector<int>& prices) {
int r = 0;
int minPrice = prices[0];
for (const int& price : prices) {
int v = price - minPrice;
if (v < 0) {
minPrice = price;
} else if (v > r) {
r = v;
}
}
return r;
}
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)