本文最后更新于 426 天前,其中的信息可能已经有所发展或是发生改变。
题目描述
- 给定一个整数数组
prices,其中prices[i]表示第i天的股票价格 ;整数fee代表了交易股票的手续费用。 - 你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
- 返回获得利润的最大值。
注意: 这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
示例1:
输入: prices = [1, 3, 2, 8, 4, 9], fee = 2
输出: 8
解释: 能够达到的最大利润:
在此处买入 prices[0] = 1
在此处卖出 prices[3] = 8
在此处买入 prices[4] = 4
在此处卖出 prices[5] = 9
总利润: ((8 – 1) – 2) + ((9 – 4) – 2) = 8
示例2:
输入: prices = [1,3,7,5,10,3], fee = 3
输出: 6
提示:
- 1 <= prices.length <= 5 * 10^4
- 1 <= prices[i] <= 5 * 10^4
- 0 <= fee < 5 * 10^4
解题思路
确定dp数组以及下标的含义
确定递推公式
第
i天持有股票的情况:dp[i][0],可以由买入和不买入两种情况决定- 情况1: 第
i天 买入 股票,那么第i天所得现金为昨天不持有股票所得现金减去第i天持有股票价格:dp[i-1][1]-price[i] - 情况2: 第
i天 不买入 股票,那么第i天所得现金即第i-1天持有股票所得现金:dp[i-1][0] - 取上述两种情况的最大值,
dp[i][0] = max(dp[i-1][0], dp[i-1][1]-price[i])
- 情况1: 第
第i天不持有股票,
dp[i][1],可以由不持有和卖出两种情况决定- 情况1: 第
i-1天不持有股票,那么保持现状,第i天所得现金即第i-1天不持有股票所得现金:dp[i-1][1] - 情况2:(i-1天持有股票) 第
i天卖出股票,第i天所得现金即按照今天股票价格卖出并扣除手续费后得到:price[i] + dp[i-1][0] - fee - 取上述两种情况的最大值,
dp[i][1] = max(dp[i-1][1], price[i] + dp[i-1][0] - fee)
- 情况1: 第
dp数组初始化
确定遍历顺序
根据递推公式可以看出,打印dp数组
dp[i][0] 表示第i天持有股票所得的最多现金 dp[i][1] 表示第i天不持有股票所得的最多现金
dp[0][0]:表示第0天持有股票,就是第0天买入,即:dp[0][0] -= price[0] dp[0][1]:表示第0天不持有股票,即:dp[0][1] = 0
dp[i] 都是由 dp[i-1] 推出来的,那么遍历顺序一定是从前往后遍历
代码实现
- 核心模式
class Solution{
public:
int maxProfit(vector<int>& prices, int fee){
int len = prices.size();
if (len == 0) return 0;
vector<vector<int>> dp(len, vector(2, 0));
// initialize the DP array
dp[0][0] = -prices[0];
// traversal
for (int i = 1; i < len; i++){
dp[i][0] = max(dp[i-1][0], dp[i-1][1]-prices[i]);
dp[i][1] = max(dp[i-1][1], prices[i] + dp[i-1][0] - fee);
}
// maxProfit may appear holding or selling shears on the last day
return max(dp[len - 1][0], dp[len - 1][1]);
}
};
- ACM模式 "dynamicPro.h"
#include <iostream>
#include "dynamicPro.h"
class Solution{
public:
int maxProfit(const vector<int>& prices, int fee){
int len = prices.size();
if (len == 0) return 0;
vector<vector<int>> dp(len, vector<int>(2, 0));
// initialize the DP array
dp[0][0] = -prices[0];
// traversal
for (int i = 1; i < len; i++){
dp[i][0] = std::max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = std::max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
}
print2DVector(dp);
// maxProfit may appear holding or selling shears on the last day
return std::max(dp[len - 1][0], dp[len - 1][1]);
}
};
int main(){
vector<int> case1 = {1, 3, 2, 8, 4, 9};
vector<int> case2 = {1, 3, 7, 5, 10, 3};
Solution solution;
cout << "Result1's DP array = " << solution.maxProfit(case1, 2) << endl;
cout << "Result2's DP array = " << solution.maxProfit(case2, 3) << endl;
}
*输出
Result1's DP array = [[-1, 0], [-1, 0], [-1, 0], [-1, 5], [1, 5], [1, 8]]
8
Result2's DP array = [[-1, 0], [-1, 0], [-1, 3], [-1, 3], [-1, 6], [3, 6]]
6