Code
Time Complexity: O(n), Space Complexity: O(1)
DP - 1
Follows the tutorial of Most consistent ways of dealing with the series of stock problems, we get the following solution.
Note that index 0 is the day before the prices of stocks starts, so index 1 corresponds index 0 of the prices array.
DP - 2
Kadane’s Algorithm
由 Kadane Algorithm(Maximum Subarray Problem) 可寫成以下版本(注意因為題目給的是當日的 price,因此在計算時要自己換算成兩日之間的差):
類似題目 : Maximum Subarray
Link