@@ -26,20 +26,43 @@ def sellstock(prices):
26
26
# profit = max_val - price_to_buy
27
27
# return profit
28
28
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
39
58
40
59
41
60
# prices = [7,1,5,3,6,4]
61
+ #
62
+ # prices = [7, 6, 4, 3, 1]
63
+
64
+ prices = [2 , 1 , 4 ]
42
65
43
- prices = [7 , 6 , 4 , 3 , 1 ]
66
+ # prices = [2, 4 , 1]
44
67
45
- print (sellstock (prices ))
68
+ print (sellstock (prices ))
0 commit comments