Skip to content

Commit 0b417f2

Browse files
committed
add max profit algorithm
1 parent 685aa2e commit 0b417f2

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

arrays/max_profit.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
buy-sell stock:
3+
max_profit([7, 1, 5, 3, 6, 4]) => 5
4+
max_profit([9, 7, 6, 4, 3, 1]) => 0
5+
complexity: O(n)
6+
"""
7+
8+
from typing import List
9+
10+
11+
def max_profit(prices: List[int]) -> int:
12+
profitable_stocks = {}
13+
for first, second in zip(prices, prices[1:]):
14+
distance = second - first
15+
if distance > 0:
16+
profitable_stocks[(first, second)] = distance
17+
if not profitable_stocks:
18+
return 0
19+
best_match = max(
20+
profitable_stocks,
21+
key=lambda key: profitable_stocks[key]
22+
)
23+
return best_match[1]
24+
25+
26+
if __name__ == "__main__":
27+
print(max_profit([7, 1, 5, 3, 6, 4]) == 5)
28+
print(max_profit([9, 7, 6, 4, 3, 1]) == 0)

0 commit comments

Comments
 (0)