forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-profitable-triplets-with-increasing-prices-ii.py
258 lines (229 loc) · 9.02 KB
/
maximum-profitable-triplets-with-increasing-prices-ii.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# Time: O(nlogn)
# Space: O(n)
import itertools
from sortedcontainers import SortedList
# prefix sum, sorted list, binary search, mono stack
class Solution(object):
def maxProfit(self, prices, profits):
"""
:type prices: List[int]
:type profits: List[int]
:rtype: int
"""
NEG_INF = float("-inf")
def query(sl, k):
j = sl.bisect_left((k,))
return sl[j-1][1] if j-1 >= 0 else NEG_INF
def update(sl, k, v):
j = sl.bisect_left((k,))
if j < len(sl) and sl[j][0] == k:
if not (sl[j][1] < v):
return
del sl[j]
elif not (j-1 < 0 or sl[j-1][1] < v):
return
sl.add((k, v))
while j+1 < len(sl) and sl[j+1][1] <= sl[j][1]:
del sl[j+1]
result = NEG_INF
sl1, sl2 = SortedList(), SortedList()
for price, profit in itertools.izip(prices, profits):
result = max(result, query(sl2, price)+profit)
update(sl1, price, profit)
update(sl2, price, query(sl1, price)+profit)
return result if result != NEG_INF else -1
# Time: O(nlogn)
# Space: O(n)
from sortedcontainers import SortedList
# prefix sum, sorted list, binary search, mono stack
class Solution2(object):
def maxProfit(self, prices, profits):
"""
:type prices: List[int]
:type profits: List[int]
:rtype: int
"""
NEG_INF = float("-inf")
right = [NEG_INF]*len(prices)
sl = SortedList()
for i in reversed(xrange(len(prices))):
j = sl.bisect_left((-prices[i],))
if j-1 >= 0:
right[i] = sl[j-1][1]
if not (j-1 < 0 or sl[j-1][1] < profits[i]):
continue
sl.add((-prices[i], profits[i]))
j = sl.bisect_left((-prices[i], profits[i]))
while j+1 < len(sl) and sl[j+1][1] <= sl[j][1]:
del sl[j+1]
result = NEG_INF
sl = SortedList()
for i in xrange(len(prices)):
j = sl.bisect_left((prices[i],))
if j-1 >= 0:
result = max(result, sl[j-1][1]+profits[i]+right[i])
if not (j-1 < 0 or sl[j-1][1] < profits[i]):
continue
sl.add((prices[i], profits[i]))
j = sl.bisect_left((prices[i], profits[i]))
while j+1 < len(sl) and sl[j+1][1] <= sl[j][1]:
del sl[j+1]
return result if result != NEG_INF else -1
# Time: O(nlogn)
# Space: O(n)
import itertools
# prefix sum, bit, fenwick tree
class Solution3(object):
def maxProfit(self, prices, profits):
"""
:type prices: List[int]
:type profits: List[int]
:rtype: int
"""
NEG_INF = float("-inf")
class BIT(object): # 0-indexed.
def __init__(self, n, default=0, fn=lambda x, y: x+y):
self.__bit = [NEG_INF]*(n+1) # Extra one for dummy node.
self.__default = default
self.__fn = fn
def update(self, i, val):
i += 1 # Extra one for dummy node.
while i < len(self.__bit):
self.__bit[i] = self.__fn(self.__bit[i], val)
i += (i & -i)
def query(self, i):
i += 1 # Extra one for dummy node.
ret = self.__default
while i > 0:
ret = self.__fn(ret, self.__bit[i])
i -= (i & -i)
return ret
price_to_idx = {x:i for i, x in enumerate(sorted(set(prices)))}
result = NEG_INF
bit1, bit2 = BIT(len(price_to_idx), default=NEG_INF, fn=max), BIT(len(price_to_idx), default=NEG_INF, fn=max)
for price, profit in itertools.izip(prices, profits):
result = max(result, bit2.query(price_to_idx[price]-1)+profit)
bit1.update(price_to_idx[price], profit)
bit2.update(price_to_idx[price], bit1.query(price_to_idx[price]-1)+profit)
return result if result != NEG_INF else -1
# Time: O(nlogn)
# Space: O(n)
import itertools
# prefix sum, segment tree
class Solution4(object):
def maxProfit(self, prices, profits):
"""
:type prices: List[int]
:type profits: List[int]
:rtype: int
"""
NEG_INF = float("-inf")
# Range Maximum Query
class SegmentTree(object):
def __init__(self, N,
build_fn=lambda _: None,
query_fn=lambda x, y: max(x, y),
update_fn=lambda x, y: max(x, y)):
self.tree = [None]*(2*2**((N-1).bit_length()))
self.base = len(self.tree)//2
self.query_fn = query_fn
self.update_fn = update_fn
for i in xrange(self.base, self.base+N):
self.tree[i] = build_fn(i-self.base)
for i in reversed(xrange(1, self.base)):
self.tree[i] = query_fn(self.tree[2*i], self.tree[2*i+1])
def update(self, i, h):
x = self.base+i
self.tree[x] = self.update_fn(self.tree[x], h)
while x > 1:
x //= 2
self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])
def query(self, L, R):
if L > R:
return None
L += self.base
R += self.base
left = right = None
while L <= R:
if L & 1:
left = self.query_fn(left, self.tree[L])
L += 1
if R & 1 == 0:
right = self.query_fn(self.tree[R], right)
R -= 1
L //= 2
R //= 2
return self.query_fn(left, right)
price_to_idx = {x:i for i, x in enumerate(sorted(set(prices)))}
result = NEG_INF
st1, st2 = SegmentTree(len(price_to_idx)), SegmentTree(len(price_to_idx))
for price, profit in itertools.izip(prices, profits):
mx2 = st2.query(0, price_to_idx[price]-1)
if mx2 is not None:
result = max(result, mx2+profit)
st1.update(price_to_idx[price], profit)
mx1 = st1.query(0, price_to_idx[price]-1)
if mx1 is not None:
st2.update(price_to_idx[price], mx1+profit)
return result if result != NEG_INF else -1
# Time: O(nlogn)
# Space: O(n)
# prefix sum, segment tree
class Solution5(object):
def maxProfit(self, prices, profits):
"""
:type prices: List[int]
:type profits: List[int]
:rtype: int
"""
NEG_INF = float("-inf")
# Range Maximum Query
class SegmentTree(object):
def __init__(self, N,
build_fn=lambda _: None,
query_fn=lambda x, y: max(x, y),
update_fn=lambda x, y: max(x, y)):
self.tree = [None]*(2*2**((N-1).bit_length()))
self.base = len(self.tree)//2
self.query_fn = query_fn
self.update_fn = update_fn
for i in xrange(self.base, self.base+N):
self.tree[i] = build_fn(i-self.base)
for i in reversed(xrange(1, self.base)):
self.tree[i] = query_fn(self.tree[2*i], self.tree[2*i+1])
def update(self, i, h):
x = self.base+i
self.tree[x] = self.update_fn(self.tree[x], h)
while x > 1:
x //= 2
self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])
def query(self, L, R):
if L > R:
return None
L += self.base
R += self.base
left = right = None
while L <= R:
if L & 1:
left = self.query_fn(left, self.tree[L])
L += 1
if R & 1 == 0:
right = self.query_fn(self.tree[R], right)
R -= 1
L //= 2
R //= 2
return self.query_fn(left, right)
price_to_idx = {x:i for i, x in enumerate(sorted(set(prices)))}
right = [NEG_INF]*len(prices)
st = SegmentTree(len(price_to_idx))
for i in reversed(xrange(len(prices))):
right[i] = st.query(price_to_idx[prices[i]]+1, len(price_to_idx)-1)
st.update(price_to_idx[prices[i]], profits[i])
result = NEG_INF
st = SegmentTree(len(price_to_idx))
for i in xrange(len(prices)):
left = st.query(0, price_to_idx[prices[i]]-1)
if left is not None and right[i] is not None:
result = max(result, left+profits[i]+right[i])
st.update(price_to_idx[prices[i]], profits[i])
return result if result != NEG_INF else -1