Skip to content

Commit 6f9403f

Browse files
committed
Time: 304 ms (50.89%), Space: 33.6 MB (90.39%) - LeetHub
1 parent 2809588 commit 6f9403f

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def maxProfit(self, prices: List[int], strategy: List[int], k: int) -> int:
8+
n = len(prices)
9+
10+
base = sum(p * s for p, s in zip(prices, strategy))
11+
12+
half = k // 2
13+
14+
conPrefix = [0]*(n+1)
15+
for i in range(n):
16+
conPrefix[i+1] = conPrefix[i] + strategy[i]*prices[i]
17+
18+
pricePrefix = [0]*(n+1)
19+
for i in range(n):
20+
pricePrefix[i+1] = pricePrefix[i] + prices[i]
21+
22+
bestDelta = 0
23+
24+
for l in range(n-k+1):
25+
mid = l+half
26+
r = l+k
27+
28+
loss = conPrefix[mid] - conPrefix[l]
29+
30+
gain = (pricePrefix[r] - pricePrefix[mid]) - \
31+
(conPrefix[r] - conPrefix[mid])
32+
33+
delta = -loss + gain
34+
if delta > bestDelta:
35+
bestDelta = delta
36+
37+
return base + bestDelta
38+
39+
40+
prices = [4, 2, 8]
41+
strategy = [-1, 0, 1]
42+
k = 2
43+
print(Solution().maxProfit(prices, strategy, k))
44+
prices = [5, 4, 3]
45+
strategy = [1, 1, 0]
46+
k = 2
47+
print(Solution().maxProfit(prices, strategy, k))

0 commit comments

Comments
 (0)