解法:动态规划
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
if(prices.size()<2) return 0;
int n=prices.size();
//状态:dp[n][t]表示第n天,t=1表示持有股票或t=0表示不持有股票时的最大收益
int dp[n][2]={0};
//初始化
dp[0][0]=0;
dp[0][1]=-prices[0];
//传递方程
for(int i=1;i<n;i++){
dp[i][0]=max(dp[i-1][0],dp[i-1][1]+prices[i]-fee);
dp[i][1]=max(dp[i-1][1],dp[i-1][0]-prices[i]);
}
return dp[n-1][0]; //结果
}
};