LeetCode HOT100 - 买卖股票的最佳时机

就是在买入后在最高价卖出

因此找后缀最大值

class Solution {
public:
    int maxProfit(vector<int>& a) {
        int n = a.size();
        int mx = -1;
        int ans = 0;
        for (int i = n - 1; i >= 0; i--) {
            if (mx > a[i]) {
                ans = max(ans, mx - a[i]);
            }
            mx = max(a[i], mx);
        }
        return ans;
    }
};
posted @ 2026-03-31 15:45  rdcamelot  阅读(10)  评论(0)    收藏  举报