Skip to content

Commit 9c08a05

Browse files
author
Мето Трајковски
committed
Update max_profit_k_transactions.py
1 parent c5e317d commit 9c08a05

1 file changed

Lines changed: 7 additions & 5 deletions

File tree

Dynamic Programming/max_profit_k_transactions.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
given k transactions. Note that you can only hold 1 share of the stock at a time; in other words,
1010
you cannot buy more than 1 share of the stock on any given day, and you cannot buy a share of the
1111
stock if you are still holding another share.
12+
In a day, you can first sell a share and buy another after that.
1213
1314
Input: [5, 11, 3, 50, 60, 90], 2
1415
Output: 93
@@ -37,8 +38,9 @@ def max_profit_with_k_transactions(prices, k):
3738
return 0
3839

3940
# transaction = buy + sell (2 separate days)
40-
# max transactions should be half from the days
41-
k = min(k, days // 2)
41+
# in a day you can sell and after that buy a share
42+
# (according to this, can't exists more transactions than the number of the prices/days)
43+
k = min(k, days)
4244
# create space optimized dp matrix
4345
dp = [[0 for j in range(days)] for i in range(2)]
4446

@@ -51,14 +53,14 @@ def max_profit_with_k_transactions(prices, k):
5153

5254
# the values in dp table for these days will be same
5355
# just ignore them, don't update them (because those combinations were tried)
54-
past_days = 2 * t
56+
past_days = t
5557
# only save the last one
5658
dp[curr_idx][past_days] = dp[prev_idx][past_days]
5759

5860
for d in range(past_days + 1, days):
59-
# first try to sell with the current price
61+
# first try to buy with the current price
6062
max_prev = max(max_prev, dp[prev_idx][d - 1] - prices[d - 1])
61-
# after that try to buy with the current price
63+
# after that try to sell with the current price
6264
dp[curr_idx][d] = max(dp[curr_idx][d - 1], max_prev + prices[d])
6365

6466
# return the last value from the last transaction

0 commit comments

Comments
 (0)