Question
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 = 2Output: 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.
问题解析:
给定数组,其中的元素代表当天的股票价格,不限制股票的购售次数,但要求在购买新股之前要售出之前的股票,求股票交易的最大利润。每次股票交易都要支付固定的交易费。
Answer
Solution 1:
DP。
- 与之前的
LeetCode-121:Best Time to Buy and Sell Stock (一次股票交易最大利润)
和LeetCode-122:Best Time to Buy and Sell Stock II (多次股票交易最大利润)
相似,均为股票交易题目,但本题增加了交易费的条件。 - 分析每天的行为,我们可以知道,主要的行为就是售出和购入。所以我们建立两个动态规划数组:sold和hold,其中
sold[i]
保存的是第i天出售股票后的最大利润,hold[i]
保存的是第i天持有股票的最大利润。 sold[i]
有两个状态,一个是在i天售出的利润,或者保持前一天也就是sold[i-1]
的售出利润,选择其中的最大利润。hold[i]
也有两个状态,一个是在i天购入的利润,或者保持前一天也就是hold[i-1]
的持有利润,选择其中的最大利润。- 写为动态规划式为:
Soldi=Max(Soldi−1,Holdi−1+Pricesi−fee); Holdi=Max(Holdi,Soldi−1−Pricesi)
class Solution {
public int maxProfit(int[] prices, int fee) {
int n = prices.length;
if (n < 2) return 0;
int[] sold = new int[n];
int[] hold = new int[n];
hold[0] = -prices[0];
for (int i = 1; i < n; i++){
sold[i] = Math.max(sold[i-1], hold[i-1] + prices[i] - fee);
hold[i] = Math.max(hold[i-1], sold[i-1] - prices[i]);
}
return sold[n-1];
}
}
- 时间复杂度:O(n),空间复杂度:O(n)
Solution 2:
DP优化。
- 同样,与
LeetCode-152:Maximum Product Subarray (乘积最大连续子数组)
相同,Solution 1 的解法可以做空间上的优化。因为动态规划公式中每次计算使用的只有上一次的结果,所以,我们将前一次的结果做临时的保存即可实现空间上的优化。
class Solution {
public int maxProfit(int[] prices, int fee) {
int n = prices.length;
if (n < 2) return 0;
int sold = 0;
int hold = -prices[0];
for (int i = 1; i < n; i++){
int soldpre = sold;
sold = Math.max(soldpre, hold + prices[i] - fee);
hold = Math.max(hold, soldpre - prices[i]);
}
return sold;
}
}
- 时间复杂度:O(n),空间复杂度:O(1)