与上一题的区别在于不限制交易次数
修改状态dp[天数][持有股票数]
状态转移方程为
dp[i][1][1]=max(dp[i-1][1], dp[i-1][0]-price[i])//昨天买入或今天买入
dp[i][1][0]=max(dp[i-1][0], dp[i-1][1]+price[i])//昨天卖出或今天卖出
int maxProfit(int* prices, int pricesSize) {
if (pricesSize <= 1) {
return 0; // 没有足够的数据进行交易,利润为0
}
int i;
int (*dp)[2] = malloc(pricesSize * sizeof(int[2]));
dp[0][1] = -prices[0];
dp[0][0] = 0;
for (i = 1; i < pricesSize; i++) {
dp[i][1] = fmax(dp[i - 1][1], dp[i-1][0]-prices[i]);
dp[i][0] = fmax(dp[i - 1][0], dp[i - 1][1] + prices[i]);
}
int maxProfit = dp[pricesSize - 1][0];
free(dp); // 释放动态分配的内存
return maxProfit;
}
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size(), memo[n][2];
memset(memo,0,sizeof(memo));
memo[0][0]=0;
memo[0][1]= -prices[0];
for(int i=1;i<n;i++){
memo[i][0]=max(memo[i-1][0],memo[i-1][1]+prices[i]);
memo[i][1]=max(memo[i-1][1],memo[i-1][0]-prices[i]);
}
return memo[n-1][0];
}
};