714 . 买卖股票的最佳时机含手续费
题目:给定一个整数数组 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.
方法一:
class Solution { public: int maxProfit(vector<int>& prices, int fee) { int n = prices.size(); if(n <= 1) return 0; vector<vector<int>> dp(n, vector<int> (2)); // 初始化 dp[0][0] = 0; dp[0][1] = -prices[0]; // 买入的股票 for(int i = 1; i < n; i++) { dp[i][0] = max(dp[i - 1][0], prices[i] + dp[i - 1][1] - fee); dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]); } return dp[n - 1][0]; } };
方法二: class Solution { public: int maxProfit(vector<int>& prices, int fee) { int n = prices.size(); if(n <= 1) return 0; //滚动数组:用cash和stock动态记录现金和股票 //初始状态下的现金为0 int cash = 0; //初始状态下买入第一支股票为负 int stock = -prices[0]; for(int i = 1; i < n; i++) { //现金=上一次的现金 与 当前股票价格+上一次买入股票后的余额-此次操作的费用(卖出股票)的极大值 cash = max(cash, prices[i] + stock - fee); //买入股票后的余额 = 上一次买入股票后的余额 与 当前持有现金减去当前股票价格所获得的的金额 stock = max(stock, cash - prices[i]); } return cash; } };