Skip to content

Commit bba3978

Browse files
authored
Add files via upload
1 parent 6885d94 commit bba3978

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Sliding_Windows/buy_sell_stocks.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
def max_profit(prices):
2+
if not prices:
3+
return 0
4+
5+
min_price = float('inf') # Initialize to a very high value
6+
max_profit = 0 # Initialize max profit
7+
8+
for price in prices:
9+
# Update the minimum price if the current price is lower
10+
if price < min_price:
11+
min_price = price
12+
13+
# Calculate the profit if selling at the current price
14+
profit = price - min_price
15+
16+
# Update max profit if the calculated profit is higher
17+
if profit > max_profit:
18+
max_profit = profit
19+
20+
return max_profit
21+
22+
23+
# Driver code with test cases
24+
test_cases = [
25+
[1, 2, 4, 2, 5, 7, 2, 4, 9, 0, 9],
26+
[7, 1, 5, 3, 6, 4],
27+
[7, 6, 4, 3, 1],
28+
[2, 6, 8, 7, 8, 7, 9, 4, 1, 2, 4, 5, 8],
29+
[1, 4, 2]
30+
]
31+
32+
for i, prices in enumerate(test_cases):
33+
print(f"Test Case {i + 1}: Prices = {prices}, Max Profit = {max_profit(prices)}")

0 commit comments

Comments
 (0)