LeetCode 121 Best Time to Buy and Sell Stock(株式購入販売の最適な時間)


翻訳
i       i      。

              (  ,          ),             。

テキスト
Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), 
design an algorithm to find the maximum profit.

ぶんせき
まず、最大利益と最小利益を設定します.
現在のこの日の株価が最低価格よりも小さい場合は、最低価格をこの日の株価に設定します.
なぜこの価格を計算したのか、もちろん最大利益を計算するために舗装されています.
最大利益が当日価格から最低価格を差し引くよりも低い場合は、最大利益を当日価格から最低価格を差し引くように設定します.
コード#コード#
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        size_t size = prices.size();
        if (size <= 1) return 0;
        int min = INT_MAX, max = INT_MIN;
        for (int i = 0; i < size; ++i) {
            if (prices[i] < min)
                min = prices[i];
            if (max < prices[i] - min)
                max = prices[i] - min;
        }
        return max;
    }
};