714. 买卖股票的最佳时机含手续费
给定一个整数数组 prices
,其中第 i
个元素代表了第 i
天的股票价格 ;非负整数 fee
代表了交易股票的手续费用。
你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前就不能再继续购买股票了。
返回获得利润的最大值。
输入: 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.
//动态规划,经典版,时空都是On
func maxProfit(prices []int, fee int) int {
n := len(prices)
dp := make([][2]int, n) // dp 【】【2】 两个状态的最大值
dp[0][1] = -prices[0] // dp【i】【0】,第i天时,不在手; dp【i】【1】,在手
for i := 1; i < n; i++ {
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]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
//滚动数组,空间优化O1
func maxProfit(prices []int, fee int) int {
n := len(prices)
sell, buy := 0, -prices[0]
for i := 1; i < n; i++ {
sell = max(sell, buy + prices[i] - fee)
buy = max(buy, sell - prices[i])
}
return sell
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
//贪心算法: 得定义两个数组 buy额外定义,max存结果 On O1
func maxProfit(prices []int, fee int) int {
n := len(prices)
buy := prices[0] + fee;
max := 0;
for i := 1; i < n; i++ {
if prices[i] + fee < buy {
buy = prices[i] + fee
} else if prices[i] > buy {
max += prices[i] - buy
buy = prices[i]
}
}
return max
}