[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day, and an integer fee
representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [1,3,2,8,4,9], fee = 2 Output: 8 Explanation: The maximum profit can be achieved by: - Buying at prices[0] = 1 - Selling at prices[3] = 8 - Buying at prices[4] = 4 - Selling at prices[5] = 9 The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Example 2:
Input: prices = [1,3,7,5,10,3], fee = 3 Output: 6
Constraints:
1 <= prices.length <= 5 * 104
1 <= prices[i] < 5 * 104
0 <= fee < 5 * 104
买卖股票的最佳时机含手续费。
给定一个整数数组 prices,其中 prices[i]表示第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。
你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
返回获得利润的最大值。
注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是股票系列的最后一题了。这道题允许你交易多次,但是每次交易的时候是有一个手续费,用 fee 表示。依然是请你返回获得利润的最大值。
思路依然是动态规划。还是创建一个二维的DP数组,dp[i][j] 表示第 i 天持有和不持有股票的最大收益。j 只有可能是 0 或 1,表示不持有股票和持有股票。这道题多的一个变量 fee 可以把他理解为成本的一部分,放在买入的时候或卖出的时候都可以。其他部分跟版本二的动态规划解法没有区别,也是可以交易多次的。分享一个写的很好的题解。
时间O(n)
空间O(mn)
Java实现
1 class Solution { 2 public int maxProfit(int[] prices, int fee) { 3 int len = prices.length; 4 // corner case 5 if (len < 2) { 6 return 0; 7 } 8 9 // dp[i][j] 表示 [0, i] 区间内,到第 i 天(从 0 开始)状态为 j 时的最大收益' 10 // j = 0 表示不持股,j = 1 表示持股 11 // 并且规定在买入股票的时候,扣除手续费 12 int[][] dp = new int[len][2]; 13 dp[0][0] = 0; 14 dp[0][1] = -prices[0] - fee; 15 for (int i = 1; i < len; i++) { 16 dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]); 17 dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i] - fee); 18 } 19 return dp[len - 1][0]; 20 } 21 }