0%

LeetCode.714.买卖股票的最佳时机含手续费(中等)

题目

LeetCode.714.买卖股票的最佳时机含手续费(中等)

给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。

你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

返回获得利润的最大值。

注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。

题解

状态转移方程同LeetCode.122.买卖股票的最佳时机 II(简单)

卖出时计算利润时把交易费扣除即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
fun maxProfit(prices: IntArray, fee: Int): Int {
val n = prices.size
if (n <= 1) return 0
var noholdProfit = 0
var holdProfit = -prices[0]
for (i in 1 until n) {
noholdProfit = maxOf(noholdProfit, holdProfit + prices[i] - fee)
holdProfit = maxOf(holdProfit, noholdProfit - prices[i])
}
return noholdProfit
}
}