diff --git a/3573.Best Time to Buy and Sell Stock V.cpp b/3573.Best Time to Buy and Sell Stock V.cpp new file mode 100644 index 0000000..87bba48 --- /dev/null +++ b/3573.Best Time to Buy and Sell Stock V.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector prices; + long long mn = -1e14; + vector>> dp; + long long f(int i, int k, int state){ + if(i == prices.size()){ + return state == 0 ? 0 : mn; + } + if(dp[i][k][state] != mn) return dp[i][k][state]; + + long long p = prices[i]; + long long profit = mn; + profit = max(profit, f(i + 1, k, state)); + + if(state == 0){ + profit = max(profit, f(i+1, k, 1) - p); + profit = max(profit, f(i+1, k, 2) + p); + } + else if(k > 0){ // have transactions left + if(state == 1){ + profit = max(profit, f(i+1, k-1, 0) + p); + + } + else{ + profit = max(profit, f(i+1, k-1, 0) - p); + } + } + return dp[i][k][state] = profit; + } + + long long maximumProfit(vector& prices, int k) { + this->prices = prices; + dp.assign(prices.size() + 1, vector> (k + 1, vector (3, mn))); + return f(0, k, 0); + } +}; \ No newline at end of file