Skip to content

Commit 24a6c67

Browse files
committed
add: best time to buy and sell stock
1 parent 3569f0c commit 24a6c67

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# first attempt - time out
2+
3+
class Solution:
4+
def maxProfit(self, prices: List[int]) -> int:
5+
max_profit = 0
6+
for i in range(len(prices)):
7+
profit = max(prices[i:]) - prices[i]
8+
max_profit = max(max_profit, profit)
9+
return max_profit
10+
11+
# second attempt - greedy approach
12+
class Solution:
13+
def maxProfit(self, prices: List[int]) -> int:
14+
max_profit = 0
15+
min_price = prices[0]
16+
17+
for i in range(len(prices)):
18+
min_price = min(min_price, prices[i])
19+
profit = prices[i] - min_price
20+
max_profit = max(max_profit, profit)
21+
return max_profit

0 commit comments

Comments
 (0)