【LeetCode】714. Best Time to Buy and Sell Stock with Transaction Fee 买卖股票的最佳时机含手续费(Medium)(JAVA)
题目地址: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
题目描述:
Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
Return the maximum profit you can make.
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.
Note:
- 0 < prices.length <= 50000.
- 0 < prices[i] < 50000.
- 0 <= fee < 50000.
题目大意
给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。
你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
返回获得利润的最大值。
注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
解题方法
- 和以前买卖股票的题类似,这一题就是多了交易费,买卖股票的题其实都可以用动态规划:用两种状态标识当前的最大值,dp[i][0] 第 i 个持有股票的最大值,dp[i][1] 第 i 个不持有股票的最大值
- 然后分别计算 dp[i][0] 和 dp[i][1]
- 第 i 个持有股票的最大值 dp[i][0]: dp[i - 1] 不持有股票和持有股票两种状态的最大值求出来即可;上次不持有股票的话,这次必须持有股票 dp[i - 1][1] - prices[i],上次持有的话,这次不重新持股票 dp[i - 1][0]
- 第 i 个不持有股票的最大值 dp[i][1]: 同样 dp[i - 1] 不持有股票和持有股票两种状态的最大值求出来即可;上次持有股票的话,这次必须卖出股票 dp[i - 1][0] + prices[i] - fee,上次不持有的话,这次不新持股票 dp[i - 1][1]
class Solution {
public int maxProfit(int[] prices, int fee) {
if (prices.length <= 1) return 0;
// dp[i][0]: has stock; dp[i][1]: has not stock;
int[][] dp = new int[prices.length][2];
dp[0][0] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i][0] = Math.max(dp[i - 1][1] - prices[i], dp[i - 1][0]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
}
return dp[prices.length - 1][1];
}
}
执行耗时:21 ms,击败了40.27% 的Java用户
内存消耗:47.8 MB,击败了47.88% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)