Skip to content

Commit 2fbd0da

Browse files
committed
Best Time to Buy and Sell Stock III
1 parent 4f483fc commit 2fbd0da

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'''
2+
Say you have an array for which the ith element is the price of a given stock on day i.
3+
4+
Design an algorithm to find the maximum profit. You may complete at most two transactions.
5+
6+
Note:
7+
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
8+
'''
9+
10+
class Solution(object):
11+
def maxProfit(self, prices):
12+
"""
13+
:type prices: List[int]
14+
:rtype: int
15+
"""
16+
total_max_profit = 0
17+
n = len(prices)
18+
first_profits = [0] * n
19+
min_price = float('inf')
20+
21+
for i in range(n):
22+
min_price = min(min_price, prices[i])
23+
total_max_profit = max(total_max_profit, prices[i] - min_price)
24+
first_profits[i] = total_max_profit
25+
26+
max_profit = 0
27+
max_price = float('-inf')
28+
for i in range(n - 1, 0, -1):
29+
max_price = max(max_price, prices[i])
30+
max_profit = max(max_profit, max_price - prices[i])
31+
total_max_profit = max(total_max_profit, max_profit + first_profits[i - 1])
32+
return total_max_profit
33+
34+
35+
if __name__ == "__main__":
36+
assert Solution().maxProfit([2, 4, 6, 1, 3, 8, 3]) == 11
37+
assert Solution().maxProfit([1, 2]) == 1

0 commit comments

Comments
 (0)