题意:给出一个股票多天的价格,可以有无数次成对的买入卖出,但每次有手续费。求所能获得的最大利润
思路与分析:这是一道动态规划的问题,一共就有两种状态,当前持有股票以及没有股票。我们可以用两个变量(hold,cash)分别代表这两个状态下当前赚的最多的钱。所以在遍历过程中有:cash=max{cash,hold+prices[i]-fee},hold=max{hold,cash-prices[i]}
代码:
class Solution {
public://两种状态,一种是当前持有时的目前最大获益,一种是当前不持有时的目前最大获益
int maxProfit(vector<int>& prices, int fee) {
if (prices.size() == 0) return 0;
int hold = -prices[0], cash = 0;
for (int i = 1; i < prices.size(); i++) {
if (cash < hold + prices[i] - fee) cash = hold + prices[i] - fee;
if (cash - prices[i] > hold) hold = cash - prices[i];
}
return cash;
}
};