-
Notifications
You must be signed in to change notification settings - Fork 43
/
best-time-to-buy-and-sell-stock-iii.py
99 lines (73 loc) · 2.83 KB
/
best-time-to-buy-and-sell-stock-iii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""
123. Best Time to Buy and Sell Stock III
Hard
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 105
"""
# V0
# V1
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/solution/
# IDEA : Bidirectional Dynamic Programming
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) <= 1:
return 0
left_min = prices[0]
right_max = prices[-1]
length = len(prices)
left_profits = [0] * length
# pad the right DP array with an additional zero for convenience.
right_profits = [0] * (length + 1)
# construct the bidirectional DP array
for l in range(1, length):
left_profits[l] = max(left_profits[l-1], prices[l] - left_min)
left_min = min(left_min, prices[l])
r = length - 1 - l
right_profits[r] = max(right_profits[r+1], right_max - prices[r])
right_max = max(right_max, prices[r])
max_profit = 0
for i in range(0, length):
max_profit = max(max_profit, left_profits[i] + right_profits[i+1])
return max_profit
# V1'
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/solution/
# IDEA : One-pass Simulation
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
t1_cost, t2_cost = float('inf'), float('inf')
t1_profit, t2_profit = 0, 0
for price in prices:
# the maximum profit if only one transaction is allowed
t1_cost = min(t1_cost, price)
t1_profit = max(t1_profit, price - t1_cost)
# reinvest the gained profit in the second transaction
t2_cost = min(t2_cost, price - t1_profit)
t2_profit = max(t2_profit, price - t2_cost)
return t2_profit
# V2