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:
Note:
解法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]
|
|