面试经典150题 P121 买股票的最佳时机 Created:2025-10-01 14:39:13Updated:2025-10-01 14:39:13algorithmalgorithm, leetcode热题100, leetcode面试经典150题, 数组, 贪心字数 191阅读 访客 时间轴 时间轴2025-10-01init 数组 题目:P121 买卖股票的最佳时机https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/?envType=study-plan-v2&envId=top-interview-150维护两个值即可,一个是当前最低的价格,一个是历史最大利润。每次都假设是今天卖出,然后求今天之前的历史最低点。而这个历史最低点并不需要额外遍历,而是每天考虑的时候顺带记录的。12345678910111213141516171819#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; }};