Skip to content

Commit 48f2c43

Browse files
committed
update 188
1 parent 8377171 commit 48f2c43

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

leetcode/188.best-time-to-buy-and-sell-stock-iv.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,24 @@
2929
//
3030
//
3131

32+
class Solution {
33+
public:
34+
int maxProfit(int k, vector<int>& prices) {
35+
k = min(k, (int)prices.size() / 2);
36+
vector<int> buy = vector<int>(k + 1, INT_MIN);
37+
vector<int> sell = vector<int>(k + 1, 0);
38+
39+
for (auto p: prices) {
40+
for (int i = 1; i <= k; i++) {
41+
buy[i] = max(buy[i], sell[i - 1] - p);
42+
sell[i] = max(sell[i], buy[i] + p);
43+
}
44+
}
45+
46+
return *max_element(sell.begin(), sell.end());
47+
}
48+
};
49+
3250
class Solution {
3351
public:
3452
int maxProfit(int k, vector<int>& prices) {

leetcode/188.best-time-to-buy-and-sell-stock-iv.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,20 @@
2929
#
3030
#
3131

32+
class Solution:
33+
def maxProfit(self, k: int, prices: List[int]) -> int:
34+
k = min(k, len(prices) // 2)
35+
36+
buy = [float('-inf') for i in range(k + 1)]
37+
sell = [0 for i in range(k + 1)]
38+
39+
for p in prices:
40+
for i in range(1, k + 1):
41+
buy[i] = max(buy[i], sell[i - 1] - p)
42+
sell[i] = max(sell[i], buy[i] + p)
43+
44+
return max(sell)
45+
3246
class Solution:
3347
def maxProfit(self, k: int, prices: List[int]) -> int:
3448
if k >= len(prices):

0 commit comments

Comments
 (0)