算法随想Day44【动态规划】| LC123-买卖股票的最佳时机Ⅲ、LC188-买卖股票的最佳时机Ⅳ
LC123. 买卖股票的最佳时机Ⅲ
更多的状态转移:
- dp[i] [0]含义:第一次持有股票的最多现金
- dp[i] [1]含义:第一次不持有股票的最多现金
- dp[i] [2]含义:第二次持有股票的最多现金
- dp[i] [3]含义:第二次不持有股票的最多现金
////自写的一般实现方法
int maxProfit(vector<int>& prices)
{
int purchase = prices[0];
int maxProfit = 0;
int todayProfit = 0;
for (int i = 1; i < prices.size(); ++i)
{
todayProfit = prices[i] - purchase;
if (todayProfit > maxProfit)
{
maxProfit = todayProfit;
}
if (prices[i] < purchase)
{
purchase = prices[i];
}
}
return maxProfit;
}
LC188. 买卖股票的最佳时机Ⅳ
有了之前那么多题目的基础,这道题修改下也就写出来了
int maxProfit(int k, vector<int>& prices)
{
int size = prices.size();
vector<vector<int>> dp(size, vector<int>(1 + 2 * k, 0));
dp[0][0] = 0;
for (int i = 1; i <= 2 * k; ++i)
{
if (i % 2 == 0) //偶数下标即为0
dp[0][i] = 0;
else
dp[0][i] = -prices[0];
}
for (int i = 1; i < size; ++i)
{
dp[i][0] = dp[i - 1][0];
for (int j = 1; j <= 2 * k; ++j)
{
if (j % 2 == 0) //偶数下标即为0
{
int a = dp[i - 1][j];
int b = dp[i - 1][j - 1];
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] + prices[i]);
}
else
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] - prices[i]); //奇数下标为买入
}
}
return dp[size - 1][2 * k];
}

浙公网安备 33010602011771号