代码随想录刷题60Day
目录
前言
本日着重于多状态问题的处理,各状态之间会有一定联系,状态转移方程将不再局限一个。
买卖股票的最佳时机1
cpp
int maxProfit(vector<int>& prices)
{
int size = prices.size();
vector<vector<int>> dp(2, vector<int>(2));
dp[0][0] -= prices[0];
dp[0][1] = 0;
for (int i = 1; i < size; i++)
{
dp[i % 2][0] = max(dp[(i - 1) % 2][0], -prices[i]);
dp[i % 2][1] = max(dp[(i - 1) % 2][1], prices[i] + dp[(i - 1) % 2][0]);
}
return dp[(size - 1) % 2][1];
}
买卖股票的最佳时机2
cpp
int maxProfit1(vector<int>& prices)
{
const int size = prices.size();
vector<vector<int>> dp(2, vector<int> (2, 0));
dp[0][1] = -prices[0];
for (int i = 1; i < size; ++i)
{
dp[i % 2][0] = max(dp[(i - 1) % 2][0], dp[(i - 1) % 2][1] + prices[i]);
dp[i % 2][1] = max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] - prices[i]);
}
return dp[(size - 1) % 2][0];
}
买卖股票的最佳时机3
cpp
int maxProfit(vector<int>& prices)
{
//---------case 1--------------
int size = prices.size();
vector<vector<int>> dp(size, vector<int>(5, 0));
dp[0][1] = -prices[0];
dp[0][3] = -prices[0];
for (int i = 1; i < size; ++i)
{
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
dp[i][2] = max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
dp[i][4] = max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
}
return dp[size - 1][4];
//----------case 2--------------
int size = prices.size();
vector<vector<int>> dp(2, vector<int>(4, 0));
dp[0][0] = -prices[0];
dp[0][2] = -prices[0];
for (int i = 1; i < size; ++i)
{
dp[i % 2][0] = max(dp[(i - 1) % 2][0], - prices[i]);
dp[i % 2][1] = max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i]);
dp[i % 2][2] = max(dp[(i - 1) % 2][2], dp[(i - 1) % 2][1] - prices[i]);
dp[i % 2][3] = max(dp[(i - 1) % 2][3], dp[(i - 1) % 2][2] + prices[i]);
}
return dp[(size - 1) % 2][3];
}
买卖股票的最佳时机4
cpp
int maxProfit(int k, vector<int>& prices)
{
//----------------case 1------------------------
const int size = prices.size();
vector<vector<int>> dp(size, vector<int>(2 * k + 1, 0));
for (int i = 1; i <= k; ++i)
dp[0][i * 2 - 1] = -prices[0];
for (int i = 1; i < size; ++i)
{
int sign = -1;
for (int j = 1; j < (2 * k + 1); ++j)
{
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] + sign * prices[i]);
sign *= -1;
}
}
return dp[size - 1][2 * k];
//----------------case 2-----------------------
const int size = prices.size();
vector<vector<int>> dp(2, vector<int>(2 * k + 1, 0));
for (int i = 1; i <= k; ++i)
dp[0][i * 2 - 1] = -prices[0];
for (int i = 1; i < size; ++i)
{
int sign = -1;
for (int j = 1; j < (2 * k + 1); ++j)
{
dp[i % 2][j] = max(dp[(i - 1) % 2][j], dp[(i - 1) % 2][j - 1] + sign * prices[i]);
sign *= -1;
}
}
return dp[(size - 1) % 2][2 * k];
}