Skip to content

Commit 6f157ef

Browse files
best_time_to_buy_and_sell
best_time_to_buy_and_sell
1 parent a04b048 commit 6f157ef

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
def maxProfit(prices):
2+
min_price = float('inf')
3+
max_profit = 0
4+
5+
for price in prices:
6+
if price < min_price:
7+
min_price = price
8+
else:
9+
profit = price - min_price
10+
max_profit = max(max_profit, profit)
11+
12+
return max_profit
13+
14+
15+
prices = [7, 1, 5, 3, 6, 4]
16+
print(maxProfit(prices))
17+
18+
19+
####################################################################
20+
21+
def best_time_to_buy_and_sell(prices):
22+
if not prices:
23+
return 0, -1, -1 # No prices
24+
25+
min_price = prices[0]
26+
min_day = 0
27+
max_profit = 0
28+
buy_day = sell_day = 0
29+
30+
for i in range(1, len(prices)):
31+
profit = prices[i] - min_price
32+
if profit > max_profit:
33+
max_profit = profit
34+
buy_day = min_day
35+
sell_day = i
36+
37+
if prices[i] < min_price:
38+
min_price = prices[i]
39+
min_day = i
40+
41+
if max_profit == 0:
42+
print("No profit can be made.")
43+
else:
44+
print(f"Buy on day {buy_day} at price {prices[buy_day]}")
45+
print(f"Sell on day {sell_day} at price {prices[sell_day]}")
46+
print(f"Maximum Profit = {max_profit}")
47+
48+
return max_profit, buy_day, sell_day
49+
50+
# Example
51+
prices = [7, 1, 5, 3, 6, 4]
52+
best_time_to_buy_and_sell(prices)

0 commit comments

Comments
 (0)