leetcode-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 | Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 |
Note:
0 < prices.length <= 50000
.
0 < prices[i] < 50000
.
0 <= fee < 50000
.
分析
现在假设 $dp[i]$ 表示前 $i$ 个交易日所能获得的最大的利润。则 $dp[i]$ 的更新分为两种情况,一种情况是在第 $i$ 个交易日发生了卖出,另一种情况是在第 $i$ 个交易日没有发生卖出。没有发生买出,则有 $dp[i] = dp[i-1]$. 若发生了卖出,则要寻找一个 $j$ ,使得在 $j$ 发生了买入行为,则有 $dp[i] = prices[i]-prices[j]-fee+dp[j-1]$. 这时我们令 $cache = prices[j]+fee-de[j-1]$,维护这个 $cache$ 的最小值即可,很方便地在 $i$ 点求出最大利润。
代码
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/20/leetcode-714/
License: 知识共享署名-非商业性使用 4.0 国际许可协议