Skip to content

Commit b88cf40

Browse files
author
Joseph Luce
authored
Create 123_best_time_to_buy_and_sell_stock_III.md
1 parent 9b56dba commit b88cf40

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# 123. Best Time to Buy and Sell Stock III
2+
3+
## Dynamic Programming Solution
4+
- Runtime: O(N)
5+
- Space: O(N)
6+
- N = Number of elements in array
7+
8+
By using divide in conquer, we can figure out the correct times to buy twice.
9+
If you did the question, Best Time to Buy and Sell Stock I, you may apply that algothrim here.
10+
11+
The idea is to find the best transaction to the left of the price and again to the right of the price.
12+
We can use two arrays and traverse from left to right then again from right to left to find those transactions.
13+
Then its a matter of traversing a third time but on the two new arrays to find the two best transactions.
14+
15+
```
16+
class Solution:
17+
def maxProfit(self, prices: List[int]) -> int:
18+
if len(prices) == 0:
19+
return 0
20+
left_dp, right_dp = [0] * len(prices), [0] * len(prices)
21+
22+
high = low = prices[0]
23+
left_max_profit = 0
24+
for index, price in enumerate(prices): # left to right
25+
if price < low:
26+
high = low = price
27+
else:
28+
high = max(high, price)
29+
left_dp[index] = left_max_profit = max(high - low, left_max_profit)
30+
31+
high = low = prices[-1]
32+
right_max_profit = 0
33+
for index, price in enumerate(prices[::-1]): # right to left
34+
index = len(prices)-index-1
35+
if price > high:
36+
high = low = price
37+
else:
38+
low = min(low, price)
39+
right_dp[index] = right_max_profit = max(high - low, right_max_profit)
40+
41+
return max([left_dp[i]+right_dp[i] for i in range(len(prices))])
42+
```

0 commit comments

Comments
 (0)