Skip to content

Commit 97f2fbf

Browse files
authored
Create MaximizeProfitStockProblem.py
Solution to the problem buying selling stock to maximize profit. Checking the global & the current profit mechanism to get the results.
1 parent 9629aef commit 97f2fbf

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

MaximizeProfitStockProblem.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Module to return the maximum profit that can be made after buying and selling the given stocks
2+
3+
def maxProfit(price, start, end):
4+
5+
# If the stocks can't be bought
6+
if (end <= start):
7+
return 0
8+
9+
# Initialise the profit
10+
profit = 0
11+
12+
# The day at which the stock must be bought
13+
for i in range(start, end, 1):
14+
15+
# The day at which the stock must be sold
16+
for j in range(i+1, end+1):
17+
18+
# If buying the stock at ith day and selling it at jth day is profitable
19+
if (price[j] > price[i]):
20+
21+
# Update the current profit
22+
current_profit = price[j] - price[i] +\
23+
maxProfit(price, start, i - 1) + \
24+
maxProfit(price, j + 1, end)
25+
26+
# Update the maximum profit so far
27+
profit = max(profit, current_profit)
28+
29+
return profit
30+
31+
# Example Driver Code
32+
if __name__ == '__main__':
33+
price = [100, 180, 260, 310, 40, 535, 695]
34+
n = len(price)
35+
36+
print(maxProfit(price, 0, n - 1))
37+
38+
# Solution: 865
39+
40+
# This code is contributed by Laksh Gupta

0 commit comments

Comments
 (0)