1. 题目要求
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.
2. Code
DP解法:
pay用于计算买入价格
sell用于计算当前利润
DP的算法是,假定我们当前买入第一天的股票,开销是 【第一天价格】+手续费。利润0。接下来是类似滑窗的设计,数组中,只有i-1和i中的数值是有效的,其中i-1记录着之前的开销,i位置则是当前i-1处的利润-i处的价格+手续费,如果赚到的钱在买了新股,并交了手续费后赚到了钱,就买入。i位记录新的数值,否则就不买,i位记录之前的开销。这样保证买在低点。(开销为负)
接下来的利润为开销+当前卖出价,i-1初始为0,i处则是i-1买入价格+i卖出价格,即当前的balance,这样计算可以保证卖在高点。
public int maxProfit(int[] prices, int fee) { int res = 0; int size = prices.length; int[] pay = new int[size]; int[] sell = new int[size]; pay[0] = 0 - prices[0] - fee; for(int i = 0 ; i < prices.length ; i ++) { pay[i] = Math.max(pay[i - 1], sell[i - 1] - prices[i] - fee); sell[i] = Math.max(sell[i - 1], pay[i - 1] + prices[i]); } return sell[size - 1]; }