Skip to content

Commit f20fb18

Browse files
121 dd
1 parent 71ec2cd commit f20fb18

File tree

1 file changed

+35
-12
lines changed

1 file changed

+35
-12
lines changed

121_ Best Time to Buy and Sell Stock/solution.py

+35-12
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,43 @@ def sellstock(prices):
2626
# profit = max_val - price_to_buy
2727
# return profit
2828

29-
counter = max(prices)
30-
postocut = min(prices)
31-
pos = 0
32-
for i, price in enumerate(prices):
33-
if price == postocut:
34-
pos = i
35-
newlist = prices[pos:]
36-
max_val = max(newlist)
37-
profit = max_val - postocut
38-
return profit
29+
# counter = max(prices)
30+
# postocut = min(prices)
31+
# pos = 0
32+
# for i, price in enumerate(prices):
33+
# if price == postocut:
34+
# pos = i
35+
# newlist = prices[pos:]
36+
# max_val = max(newlist)
37+
# profit = max_val - postocut
38+
# return profit
39+
40+
#using 2 pointers approach
41+
max_profit = 0
42+
lenght_list = len(prices)
43+
pointer1 = 0
44+
pointer2 = 1
45+
46+
while pointer2 < lenght_list:
47+
if prices[pointer1] > prices[pointer2]:
48+
pointer1 = pointer2
49+
50+
else:
51+
check_profit = prices[pointer2] - prices[pointer1]
52+
if check_profit > max_profit:
53+
max_profit = check_profit
54+
pointer2 += 1
55+
56+
57+
return max_profit
3958

4059

4160
# prices = [7,1,5,3,6,4]
61+
#
62+
# prices = [7, 6, 4, 3, 1]
63+
64+
prices = [2, 1, 4]
4265

43-
prices = [7, 6, 4, 3, 1]
66+
#prices = [2, 4, 1]
4467

45-
print(sellstock(prices))
68+
print(sellstock(prices))

0 commit comments

Comments
 (0)