Skip to content

Commit d6c7934

Browse files
committed
Implement solution for "Best Time to Buy and Sell Stock IV"
1 parent 1089be2 commit d6c7934

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public:
3+
vector<vector<vector<int>>> dp;
4+
5+
int profit(vector<int>& prices, int i, int isBuy, int k) {
6+
if (i == prices.size() || k == 0) return 0;
7+
8+
if (dp[i][isBuy][k] != -1) return dp[i][isBuy][k];
9+
10+
int a, b;
11+
if (isBuy) {
12+
a = profit(prices, i + 1, 1, k);
13+
b = profit(prices, i + 1, 0, k) - prices[i];
14+
} else {
15+
a = profit(prices, i + 1, 0, k);
16+
b = profit(prices, i + 1, 1, k - 1) + prices[i];
17+
}
18+
19+
return dp[i][isBuy][k] = max(a, b);
20+
}
21+
22+
int maxProfit(int k, vector<int>& prices) {
23+
int n = prices.size();
24+
dp = vector<vector<vector<int>>>(n, vector<vector<int>>(2, vector<int>(k + 1, -1)));
25+
return profit(prices, 0, 1, k);
26+
}
27+
};

0 commit comments

Comments
 (0)