cpp
int maxProfit(int* prices, int pricesSize){
int len = pricesSize;
int dp[len][4];
dp[0][0] = -prices[0];
dp[0][1] = 0;
dp[0][2] = 0;
dp[0][3] = 0;
for (int i = 1; i < pricesSize; i++)
{
dp[i][0] = fmax(dp[i-1][0], fmax(dp[i-1][1] - prices[i], dp[i-1][3] - prices[i]));
dp[i][1] = fmax(dp[i-1][1], dp[i-1][2]);
dp[i][2] = dp[i-1][0] + prices[i];
dp[i][3] = dp[i-1][2];
}
return fmax(dp[len - 1][3], fmax(dp[len - 1][1], dp[len - 1][2]));
}
714. 买卖股票的最佳时机含手续费
相对122.买卖股票的最佳时机II ,本题只需要在计算卖出操作的时候减去手续费就可以了,代码几乎是一样的
cpp
int maxProfit(int* prices, int pricesSize, int fee){
int len = pricesSize;
int dp[2][2];
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < len; i++)
{
dp[i%2][0] = fmax(dp[(i-1)%2][0], dp[(i-1)%2][1]-prices[i]);
dp[i%2][1] = fmax(dp[(i-1)%2][1], prices[i] + dp[(i-1)%2][0] - fee);
}
return dp[(len-1)%2][1];
}