Try   HackMD

123. Best Time to Buy and Sell Stock III

給予一陣列 prices, prices[i] 代表第 i 天時的股票價錢,回傳我們可以在這幾天中最多可以賺到多少錢,限制最多只能做兩次買進買出。但是你不能同時在還沒賣掉手上股票前,又買入另一天的股票 (手上沒股票時才能買股票)。

Solution
class Solution { public: int maxProfit(vector<int>& prices) { int t1minCost = INT_MAX, t2minCost = INT_MAX; int t1maxProfit = 0, t2maxProfit = 0; for (int price : prices) { t1minCost = min(t1minCost, price); t1maxProfit = max(t1maxProfit, price - t1minCost); t2minCost = min(t2minCost, price - t1maxProfit); t2maxProfit = max(t2maxProfit, price - t2minCost); } return t2maxProfit; } };
  • 時間複雜度:
    O(n)
  • 空間複雜度:
    O(1)