Skip to content

Commit 8b9ca80

Browse files
authored
Merge pull request ashutosh97#163 from pruthvigh/master
Add Buy and sell stock atmost k times for a maximum profit
2 parents 5b136e2 + d2481e9 commit 8b9ca80

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'''
2+
Ref: https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-k-times/
3+
4+
'''
5+
# Python program to maximize the profit
6+
# by doing at most k transactions
7+
# given stock prices for n days
8+
9+
# Function to find out maximum profit by
10+
# buying & selling a share atmost k times
11+
# given stock price of n days
12+
def maxProfit(prices, n, k):
13+
14+
# Bottom-up DP approach
15+
profit = [[0 for i in range(k + 1)]
16+
for j in range(n)]
17+
18+
# Profit is zero for the first
19+
# day and for zero transactions
20+
for i in range(1, n):
21+
22+
for j in range(1, k + 1):
23+
max_so_far = 0
24+
25+
for l in range(i):
26+
max_so_far = max(max_so_far, prices[i] -
27+
prices[l] + profit[l][j - 1])
28+
29+
profit[i][j] = max(profit[i - 1][j], max_so_far)
30+
31+
return profit[n - 1][k]
32+
33+
# Driver code
34+
k = 2
35+
prices = [10, 22, 5, 75, 65, 80]
36+
n = len(prices)
37+
38+
print("Maximum profit is:",
39+
maxProfit(prices, n, k))
40+
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
Ref: https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-k-times/
2+
3+
4+
In share trading, a buyer buys shares and sells on a future date. Given the stock price of n days, the trader is allowed to make at most k transactions, where a new transaction can only start after the previous transaction is complete, find out the maximum profit that a share trader could have made.
5+
6+
There are various versions of the problem. If we are allowed to buy and sell only once, then we can use Maximum difference between two elements algorithm. If we are allowed to make at most 2 transactions, we can follow approach discussed here.
7+
8+
In this case, we are only allowed to make at max k transactions. The problem can be solved by using dynamic programming.
9+

0 commit comments

Comments
 (0)