🎉 One-stop destination for all your technical interview Preparation 🎉
UNLIMITED TRANSACTIONS ARE ALLOWED BUT THEY SHOULD NOT OVERLAP
[✅ 4 Solutions | Recursion to memoization | Peak & valley | simple explanation](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/1888672/4-solutions-recurion-to-memoization-peak-valley-simple-explanation) |
long getMaximumProfit(long* values, int n)
{
vector<vector<long>> dp(n + 1, vector<long>(2, 0));
dp[n][0] = dp[n][1] = 0;
for (int ind = n - 1; ind >= 0; ind--) {
for (int buy = 0; buy < 2; buy++) {
long profit = 0;
if (buy) {
long buyStock = -values[ind] + dp[ind + 1][0];
long dontBuyStock = dp[ind + 1][1];
profit = max(buyStock, dontBuyStock);
} else {
long sellStock = values[ind] + dp[ind + 1][1];
long dontSellStock = dp[ind + 1][0];
profit = max(sellStock, dontSellStock);
}
dp[ind][buy] = profit;
}
}
return dp[0][1];
}
long getMaximumProfit(long* values, int n)
{
vector<long> ahead(2, 0), curr(2, 0);
ahead[0] = ahead[1] = 0;
for (int ind = n - 1; ind >= 0; ind--) {
for (int buy = 0; buy < 2; buy++) {
long profit = 0;
if (buy) {
long buyStock = -values[ind] + ahead[0];
long dontBuyStock = ahead[1];
profit = max(buyStock, dontBuyStock);
} else {
long sellStock = values[ind] + ahead[1];
long dontSellStock = ahead[0];
profit = max(sellStock, dontSellStock);
}
curr[buy] = profit;
}
ahead = curr;
}
return ahead[1];
}
long getMaximumProfit(long* values, int n)
{
long aheadNotBuy = 0, aheadBuy = 0, currBuy = 0, currNotBuy = 0;
for (int ind = n - 1; ind >= 0; ind--) {
long sellStock = aheadNotBuy;
long dontSellStock = values[ind] + aheadBuy;
currNotBuy = max(sellStock, dontSellStock);
long dontBuyStock = -values[ind] + aheadNotBuy;
long buyStock = aheadBuy;
currBuy = max(buyStock, dontBuyStock);
aheadBuy = currBuy;
aheadNotBuy = currNotBuy;
}
return aheadBuy;
}
long getMaximumProfit(long* values, int n)
{
long aheadNotBuy = 0, aheadBuy = 0, currBuy = 0, currNotBuy = 0;
for (int ind = n - 1; ind >= 0; ind--) {
currNotBuy = max(aheadNotBuy, values[ind] + aheadBuy);
currBuy = max(aheadBuy, -values[ind] + aheadNotBuy);
aheadBuy = currBuy;
aheadNotBuy = currNotBuy;
}
return aheadBuy;
}