Code
DP - 1
Time Complexity: O(n), Space Complexity: O(n)
一脈相承 Most consistent ways of dealing with the series of stock problems,和 Best Time to Buy and Sell Stock 中的寫法一樣。
差別只在於因為沒有交易次數限制,所以
DP - 2
因為可以 Buy & Sell on the same day,因此這個問題就等價於 Maximum Subarray,解法就和 Best Time to Buy and Sell Stock 中運用 Kadane Algorithm(Maximum Subarray Problem) 的解法一樣。
Time Complexity: O(n), Space Complexity: O(1)
也可以用 DP 的概念來解:
curHold
就是買股票部位現值,因為股票是未套現的資產,因此是負的(curNotHold - prices[i]
),curNotHold
就是獲利了結的現金部位,所以用加的(curHold + prices[i]
),意思就是看當天的賣出價位是否可以 cover 你之前買進的部位的價錢。
Link