|
| 1 | +package DP.其他问题如股票; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by 周杰伦 on 2018/4/10. |
| 5 | + */ |
| 6 | +public class 需要交易费用的股票交易_多数组 { |
| 7 | + public int maxProfit(int[] prices, int fee) { |
| 8 | + if(prices.length <= 1) return 0; |
| 9 | + int[] buy = new int[prices.length]; |
| 10 | + int[] hold = new int[prices.length]; |
| 11 | + int[] skip = new int[prices.length]; |
| 12 | + int[] sell = new int[prices.length]; |
| 13 | + // the moment we buy a stock, our balance should decrease |
| 14 | + buy[0] = 0 - prices[0]; |
| 15 | + // assume if we have stock in the first day, we are still in deficit |
| 16 | + hold[0] = 0 - prices[0]; |
| 17 | + for(int i = 1; i < prices.length; i++){ |
| 18 | + // We can only buy on today if we sold stock |
| 19 | + // or skipped with empty portfolio yesterday |
| 20 | + buy[i] = Math.max(skip[i-1], sell[i-1]) - prices[i]; |
| 21 | + // Can only hold if we bought or already holding stock yesterday |
| 22 | + hold[i] = Math.max(buy[i-1], hold[i-1]); |
| 23 | + // Can skip only if we skipped, or sold stock yesterday |
| 24 | + skip[i] = Math.max(skip[i-1], sell[i-1]); |
| 25 | + // Can sell only if we bought, or held stock yesterday |
| 26 | + sell[i] = Math.max(buy[i-1], hold[i-1]) + prices[i] - fee; |
| 27 | + } |
| 28 | + // Get the max of all the 4 actions on the last day. |
| 29 | + int max = Math.max(buy[prices.length - 1], hold[prices.length - 1]); |
| 30 | + max = Math.max(skip[prices.length - 1], max); |
| 31 | + max = Math.max(sell[prices.length - 1], max); |
| 32 | + return Math.max(max, 0); |
| 33 | + } |
| 34 | +} |
0 commit comments