forked from souravjain540/Basic-Python-Programs
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximizeProfitStockProblem.py
More file actions
Latest commit
40 lines (27 loc) · 950 Bytes
/
Copy pathMaximizeProfitStockProblem.py
File metadata and controls
40 lines (27 loc) · 950 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
35
36
37
38
39
40
# Module to return the maximum profit that can be made after buying and selling the given stocks
defmaxProfit(price, start, end):
# If the stocks can't be bought
if (end<=start):
return0
# Initialise the profit
profit=0
# The day at which the stock must be bought
foriinrange(start, end, 1):
# The day at which the stock must be sold
forjinrange(i+1, end+1):
# If buying the stock at ith day and selling it at jth day is profitable
if (price[j] >price[i]):
# Update the current profit
current_profit=price[j] -price[i] +\
maxProfit(price, start, i-1) + \
maxProfit(price, j+1, end)
# Update the maximum profit so far
profit=max(profit, current_profit)
returnprofit
# Example Driver Code
if__name__=='__main__':
price= [100, 180, 260, 310, 40, 535, 695]
n=len(price)
print(maxProfit(price, 0, n-1))
# Solution: 865
# This code is contributed by Laksh Gupta