121. 买卖股票的最佳时机

题目链接

解题思路:

只需要遍历价格数组一遍,记录历史最低点,然后在每一天考虑这么一个问题:如果我是在历史最低点买进的,那么我今天卖出能赚多少钱?当考虑完所有天数之时,我们就得到了最好的答案。

C++:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.empty()) return 0;

        int minprice = prices[0], maxprofit = 0;
        for (int i = 1; i < prices.size(); ++i) {
            maxprofit = max(maxprofit, prices[i] - minprice);
            minprice = min(prices[i], minprice);
        }
        return maxprofit;
    }
};

原文地址:https://www.cnblogs.com/pursuiting/p/14602301.html