forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
best-time-to-buy-and-sell-stock-iii.py
81 lines (68 loc) · 2.51 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
# Time: O(n)
# Space: O(1)
#
# Say you have an array for which the ith element
# is the price of a given stock on day i.
#
# Design an algorithm to find the maximum profit.
# You may complete at most two transactions.
#
# Note:
# You may not engage in multiple transactions at the same time
# (ie, you must sell the stock before you buy again).
#
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
class Solution(object):
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
hold1, hold2 = float("-inf"), float("-inf")
release1, release2 = 0, 0
for i in prices:
release2 = max(release2, hold2 + i)
hold2 = max(hold2, release1 - i)
release1 = max(release1, hold1 + i)
hold1 = max(hold1, -i)
return release2
# Time: O(k * n)
# Space: O(k)
class Solution2(object):
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
return self.maxAtMostKPairsProfit(prices, 2)
def maxAtMostKPairsProfit(self, prices, k):
max_buy = [float("-inf") for _ in xrange(k + 1)]
max_sell = [0 for _ in xrange(k + 1)]
for i in xrange(len(prices)):
for j in xrange(1, min(k, i/2+1) + 1):
max_buy[j] = max(max_buy[j], max_sell[j-1] - prices[i])
max_sell[j] = max(max_sell[j], max_buy[j] + prices[i])
return max_sell[k]
# Time: O(n)
# Space: O(n)
class Solution3(object):
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
min_price, max_profit_from_left, max_profits_from_left = \
float("inf"), 0, []
for price in prices:
min_price = min(min_price, price)
max_profit_from_left = max(max_profit_from_left, price - min_price)
max_profits_from_left.append(max_profit_from_left)
max_price, max_profit_from_right, max_profits_from_right = 0, 0, []
for i in reversed(range(len(prices))):
max_price = max(max_price, prices[i])
max_profit_from_right = max(max_profit_from_right,
max_price - prices[i])
max_profits_from_right.insert(0, max_profit_from_right)
max_profit = 0
for i in range(len(prices)):
max_profit = max(max_profit,
max_profits_from_left[i] +
max_profits_from_right[i])
return max_profit