Skip to content

Commit 7a1d0fb

Browse files
committed
best time to buy and sell stock solution
1 parent 60f8363 commit 7a1d0fb

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def maxProfit(self, prices: List[int]) -> int:
3+
# When length is 1, no profit possible
4+
if len(prices) == 1:
5+
return 0
6+
7+
buy = 10 ** 5
8+
profit = 0
9+
10+
# Iterate through prices
11+
for i, price in enumerate(prices):
12+
if price < buy:
13+
buy = price
14+
15+
for j in range(i + 1, len(prices)):
16+
if prices[j] <= buy:
17+
continue
18+
19+
if prices[j] - buy > profit:
20+
profit = prices[j] - buy
21+
22+
return profit
23+
24+
# Time Complexity: O(n^2)
25+
# Space Complexity: O(1)

0 commit comments

Comments
 (0)