题目描述
给定一个整数数组 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) 链接:leetcode-cn.com/problems/be…[1] 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
动态规划三部曲
由于dp[n][0]>dp[i][1],当天不持有股票利润一定大于当天持有股票,因此返回dp[len-1][0]即可
function maxProfit(prices: number[], fee: number): number {
let len=prices.length;
// define dp
let dp=new Array(len);
for(let i=0;i<len;i++){
dp[i]=new Array(2).fill(0);
}
// init dp
dp[0][0]=0;
dp[0][1]=-prices[0];
for(let i=1;i<len;i++){
dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]+prices[i]-fee);
dp[i][1]=Math.max(dp[i-1][0]-prices[i],dp[i-1][1]);
}
console.log(dp);
return dp[len-1][0]
};
function maxProfit(prices: number[], fee: number): number {
let len:number=prices.length;
// define dp
let dp=new Array(2);
// init dp
dp[0]=0;
dp[1]=-prices[0];
for(let i=1;i<len;i++){
let temp=dp[0]
dp[0]=Math.max(dp[0],dp[1]+prices[i]-fee);
dp[1]=Math.max(temp-prices[i],dp[1]);
}
console.log(dp);
return dp[0]
};
buy
表示:最大化利益的前提下,当我们手上有一只股票时,那么他的买入最低价格。profit=prices[i]-buy
;prices[i]:buy=prices[i]
;prices[i+1]-prices[i]
,此时,加上前一天prices[i]-buy
的收益,prices[i+1]-buy
buy=prices[0]+fee
;prices[i]+fee<buy
;则我们更新最低买入价格buy;function maxProfit(prices: number[], fee: number): number {
let len=prices.length;
let buy=prices[0]+fee;
let profit=0;
for(let i=1;i<len;i++){
if(prices[i]+fee<buy){
buy=prices[i]+fee;
}else if(prices[i]>buy){
profit+=prices[i]-buy
buy=prices[i]
}
}// end of for
return profit
};
[1]https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee: https://link.juejin.cn/?target=https%3A%2F%2Fleetcode-cn.com%2Fproblems%2Fbest-time-to-buy-and-sell-stock-with-transaction-fee
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有