买卖股票的最佳时机(121)
121. 买卖股票的最佳时机 - 力扣(LeetCode)
解法:
class Solution {
public:
int maxProfit(vector<int>& prices)
{
int cur_min = prices[0];
int max_profit = 0;
for (int i = 1; i < prices.size(); ++i) {
if (prices[i] > cur_min) {
max_profit = max(max_profit, prices[i] - cur_min);
}
cur_min = min(cur_min, prices[i]);
}
return max_profit;
}
};
总结:
计算时间复杂度O(N),空间复杂度O(1)。