买卖股票的最佳时机

GitHub跳转原题关系图返回列表

扫描时只用此前最低价计算今天卖出的收益,取最大值。

OJ: leetcodecn

题目 ID: best-time-to-buy-and-sell-stock

难度:普及-

标签:贪心数组

日期: 2026-07-29 12:25

题意

给定每日股价,求一次买卖的最大利润。

思路

扫描到第 i 天时,只需知道前 i-1 天的最低价 min_price,今天卖出的利润就是 prices[i] - min_price。更新 min_price 和最大利润即可。

代码

cpp
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int mn = INT_MAX, ans = 0;
        for (int x : prices) {
            mn = min(mn, x);
            ans = max(ans, x - mn);
        }
        return ans;
    }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<int> a(n);
    for (int &x : a)
        cin >> x;
    cout << Solution().maxProfit(a) << '\n';
    return 0;
}
python
#!/usr/bin/env python3
from typing import List


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        mn, ans = float("inf"), 0
        for x in prices:
            mn = min(mn, x)
            ans = max(ans, x - mn)
        return ans


def main():
    n = int(input())
    a = list(map(int, input().split()))
    print(Solution().maxProfit(a))


if __name__ == "__main__":
    main()

复杂度

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)

总结

只需维护一个变量"此前最低价",每步计算当天卖出的利润。贪心正确性:最大利润一定在某天卖出,而最优买入日一定是此前最低价日。