贪心思路:
我们要尽可能的在少花手续费的前提下而尽可能的多赚钱,其实是一致的
所以不能像之前一样遇到大于(购买+手续费)的就操作一次,因为这样在当前卖出取不到最大收益时会浪费一次两次手续费
所以可以在卖出大于(购买+手续费)时,卖出但是更新购买费用,所以当后面如果遇到更大的时候相当于反悔了卖给最大的了
公式:res + [prices[i] - buy1(prices[j])]+ [prices[j] - buy0(prices[k] +fee)] 前面一项相当于第二次卖,后面一项相当于第一次卖
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
n = len(prices)
buy = prices[0] + fee
res = 0
for i in range(1,n):
if prices[i] +fee < buy:
buy = prices[i] +fee
elif prices[i] > buy:
res += prices[i] - buy
buy = prices[i]
return res
动态规划,手续费可以在买的时候减也可以在卖的时候减
定义dp为第i天时是否持有股票能获得的最大收益
dp[0][0] = 0 ,dp[0][1] = -prices
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
#定义dp为第i天时是否持有股票能获得的最大收益
#dp[0][0] = 0 ,dp[0][1] = -prices
n = len(prices)
dp = [[0]*2 for i in range(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
for i in range(1,n):
dp[i][0] = max(dp[i-1][0],dp[i-1][1]+prices[i]-fee)
dp[i][1] = max(dp[i-1][1],dp[i-1][0]-prices[i])
return dp[n-1][0]