- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp1.py
More file actions
Latest commit
34 lines (26 loc) · 923 Bytes
/
Copy pathp1.py
File metadata and controls
34 lines (26 loc) · 923 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Function definition
defmax_profit(stock_prices):
#check if at least two prices are there
iflen(stock_prices) <2:
raiseIndexError('At least two prices needed')
#initialize the min price and max profit
#note that byuing price minimum and selling price
#maximum gives best profit
min_price=stock_prices[0]
max_profit=stock_prices[1] -stock_prices[0] #first need to buy
foridx, current_priceinenumerate(stock_prices):
#we can not sell first, hence skip the first index
ifidx==0:
continue
#see the profit if we buy at min_price
#and sell at current price
potential_profit=current_price-min_price
#update max_profit
max_profit=max(max_profit, potential_profit)
#update min_price, so it is always the lowest
#price we have seen so far
min_price=min(min_price, current_price)
returnmax_profit
#test
stock_prices= [10,7,5,8,11,9]
printmax_profit(stock_prices)