Posted onEdited onInLeetCodeDisqus: Symbols count in article: 1.4kReading time ≈1 mins.
用当前价格减去之前的最低价格来更新全局最大差价即可
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intmaxProfit(vector<int>& prices){ int mn = INT_MAX, res = 0; for (int p : prices) { res = max(res, p - mn); mn = min(mn, p); } return res; } };
直接切入法 买卖一股,一定是第i天买,第j天卖(j > i),获利是prices[j] - prices[i] 枚举j,即第几天卖,只需要维护当前最低的买入价格prices[i] (i < j)即可
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: intmaxProfit(vector<int>& prices){ int curr_min = INT_MAX; int res = 0; int n = prices.size(); for (int i = 0; i < n; ++i) { curr_min = min(curr_min, prices[i]); res = max(res, prices[i] - curr_min); } return res; } };
maximum subarray法 dp O(n) time O(1) space
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: intmaxProfit(vector<int>& prices){ int n = prices.size(); int profit = 0; int res = 0; for (int i = 1; i < n; ++i) { profit = max(profit, 0) + prices[i] - prices[i - 1]; res = max(res, profit); } return res; } };
dp O(n) time O(n) space maximum subarray的变体 (b - a) + (c - b) + (d - c) + (e - d) = e - a