LeetCode#121 Best Time to Buy and Sell Stock

1、必须保证当前确定的最小数在最大数之前,可以等价为将当前作为最大数永远取与此区间中最小数的最大差值。

max(profit, prices[i]-minPrice)
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() == 0 || prices.size() == 1)
            return 0;
        int profit = 0;
        int minPrice = prices[0];
        for(int i = 1; i < prices.size(); i++){
            profit = max(profit, prices[i]-minPrice);
            minPrice = min(minPrice, prices[i]);
        }

        return profit;
    }
};

猜你喜欢

转载自blog.csdn.net/rpybd/article/details/81725693