This is the link for a problem I am trying to solve : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
I have come up with an approach but cannot figure out why this approach is not working even on 2nd sample test case.
This is my implementation
class Solution {
public:
int MN = (2e7)*(-1);
int f(vector<vector<int>> &dp, vector<vector<bool>> &vis, int i, int k, bool buy, bool sell, bool no, vector<int> &prices) {
if(k < 0) {
return MN;
}
if(i == prices.size()) {
return 0;
}
if(vis[i][k]) {
return dp[i][k];
}
if(buy) {
dp[i][k] = max(dp[i][k], (prices[i]*(-1) + f(dp, vis, i+1, k-1, false, true, no, prices)));
dp[i][k] = max(dp[i][k], f(dp, vis, i+1, k, buy, sell, no, prices));
}
if(sell) {
dp[i][k] = max(dp[i][k], (prices[i] + f(dp, vis, i+1, k, true, false, no, prices)));
dp[i][k] = max(dp[i][k], f(dp, vis, i+1, k, buy, sell, no, prices));
}
vis[i][k] = true;
return dp[i][k];
}
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
vector<vector<int>> dp(n, vector<int>(k+1, MN));
vector<vector<bool>> vis(n, vector<bool>(k+1));
int m = f(dp, vis, 0, k, true, false, true, prices);
return m;
}
};
Also could someone suggest any methods to debug this issue because with this much recursion it’s hard to keep track and understand.