Leetcode-买卖股票的最佳时机

27.买卖股票的最佳时机

题目内容:

Leetcode-买卖股票的最佳时机

代码及思路:

为了使得收益最大,一定是买入时价格尽可能的小,卖出时尽可能的大。这样使得差价最大化

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