LeetCode 121. 买卖股票的最佳时机

Leetcode Acwing

线性遍历 \(O(n)\)

线性扫描一下整个序列,用minp维护一下当前prices[1~i-1]中的最小值,并计算prices[i]与它的差值,以此更新一下答案。

时间复杂度

\(O(n)\)

空间复杂度

\(O(1)\)

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        for (int i = 0, minp = INT_MAX; i < prices.size(); i ++)
        {
            res = max(res, prices[i] - minp);
            minp = min(minp, prices[i]);
        }
        return res;
    }
};
posted @ 2021-01-04 20:49  alexemey  阅读(35)  评论(0)    收藏  举报