714. 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:

1
2
3
4
5
6
7
8
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:

1
2
3
0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.

解法1: Two DP process

这一系列题的推广解法非常的简洁也非常的好懂。这是一种互为影响的dp系列。一般用两个dp array解决。
一个array代表在时间i不持有股票的最大值,另一个代表在时间i持有股票的最大值。
那么可以得到这样的关系
withStock[i] = Math.max(withStock[i - 1], withoutStock[i - 1] - price)
这里表示在时间i如果买了股票的话资金池就需要减掉price
withoutStock[i] = Math.max(withoutStock[i - 1], withStock[i - 1] + price)
这里只是加入了fee,那么我们可以把它放在sell的时候或者是buy的时候就可以了。
最后最大的值一定是withoutStock[i]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int maxProfit(int[] prices, int fee) {
if (prices == null || prices.length == 0) {
return 0;
}
long tik0 = 0, tik1 = Integer.MIN_VALUE;
for (int price : prices) {
long tik0_old = tik0;
tik0 = Math.max(tik0, tik1 + price - fee);
tik1 = Math.max(tik1, tik0_old - price);
}
return (int)tik0;
}
}