From d6c79346959f42eabfed7fb26fb554af50a99542 Mon Sep 17 00:00:00 2001 From: kaif969 Date: Thu, 30 Oct 2025 01:30:37 +0530 Subject: [PATCH] Implement solution for "Best Time to Buy and Sell Stock IV" --- 188. Best Time to Buy and Sell Stock IV.cpp | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 188. Best Time to Buy and Sell Stock IV.cpp diff --git a/188. Best Time to Buy and Sell Stock IV.cpp b/188. Best Time to Buy and Sell Stock IV.cpp new file mode 100644 index 0000000..b516804 --- /dev/null +++ b/188. Best Time to Buy and Sell Stock IV.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector>> dp; + + int profit(vector& prices, int i, int isBuy, int k) { + if (i == prices.size() || k == 0) return 0; + + if (dp[i][isBuy][k] != -1) return dp[i][isBuy][k]; + + int a, b; + if (isBuy) { + a = profit(prices, i + 1, 1, k); + b = profit(prices, i + 1, 0, k) - prices[i]; + } else { + a = profit(prices, i + 1, 0, k); + b = profit(prices, i + 1, 1, k - 1) + prices[i]; + } + + return dp[i][isBuy][k] = max(a, b); + } + + int maxProfit(int k, vector& prices) { + int n = prices.size(); + dp = vector>>(n, vector>(2, vector(k + 1, -1))); + return profit(prices, 0, 1, k); + } +}; \ No newline at end of file