0714-买卖股票的最佳时机含手续费
给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。
你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
返回获得利润的最大值。
注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
示例 1:
输入:prices = [1, 3, 2, 8, 4, 9], fee = 2
输出:8
解释:能够达到的最大利润:
在此处买入 prices[0] = 1
在此处卖出 prices[3] = 8
在此处买入 prices[4] = 4
在此处卖出 prices[5] = 9
总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8
示例 2:
输入:prices = [1,3,7,5,10,3], fee = 3
输出:6
提示:
1 <= prices.length <= 5 * 104
1 <= prices[i] < 5 * 104
0 <= fee < 5 * 104
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
参考:
- https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/solution/714-mai-mai-gu-piao-tan-xin-dong-gui-xia-p3h1/
贪心 VS 动态规划
python
# 0714.买卖股票最佳时机含手续费
class Solution:
def maxProfit(self, prices: [int], fee: int) -> int:
"""
使用贪心策略,就是最低值买,最高值(如果算上手续费还盈利)就卖
找到两个点,买入日期,和卖出日期。
-买入日期:其实很好想,遇到更低点就记录一下。
-卖出日期:这个就不好算了,但也没有必要算出准确的卖出日期,只要当前价格大于(最低价格+手续费),就可以收获利润,至于准确的卖出日期,就是连续收获利润区间里的最后一天(并不需要计算是具体哪一天)。
有三种情况:
-情况一:收获利润的这一天并不是收获利润区间里的最后一天(不是真正的卖出,相当于持有股票),所以后面要继续收获利润。
-情况二:前一天是收获利润区间里的最后一天(相当于真正的卖出了),今天要重新记录最小价格了。
-情况三:不作操作,保持原有状态(买入,卖出,不买不卖)
:param prices:
:return:
"""
res = 0
minPrice = prices[0]
for i in range(1, len(prices)):
# 2.买入
if prices[i] < minPrice:
minPrice = prices[i]
# 3.保持原有状态-不买不卖
if prices[i] >= minPrice and prices[i] <= minPrice + fee:
continue
# 计算利润
if prices[i] > minPrice + fee:
res += prices[i] -minPrice - fee
# 1.更新低价, 如果遇到更高的价格,fee抵消,相当于阶段的最低买最高卖
minPrice = prices[i] - fee
return res
if __name__ == "__main__":
test = Solution()
print(test.maxProfit([1, 3, 2, 8,10, 4, 9],2))
golang
package greedy
// 贪心
func maxProfitwithFee(prices []int, fee int) int {
var sum int
minPrice := prices[0]
for i:=1;i= minPrice && prices[i] <= minPrice + fee {
continue
}
// 1.sell
if prices[i] > minPrice + fee {
sum += prices[i] - minPrice - fee
minPrice = prices[i] - fee // keypoint, higher price will be ok
}
}
return sum
}