本文主要是介绍LeetCode 0714. 买卖股票的最佳时机含手续费,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
【LetMeFly】714.买卖股票的最佳时机含手续费
力扣题目链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
给定一个整数数组 prices
,其中 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
方法一:动态规划
使用两个变量:buy
代表当前处于持仓状态下的最大收益、sell
代表当前处于“空手”状态下的最大收益。
在第一天:
- 若处于持仓状态,则说明购买了第一天的股票,当前总收益 b u y = − p r i c e s [ 0 ] buy = -prices[0] buy=−prices[0]
- 若处于空手状态,则说明第一天没有进行股票交易(因为有手续费所以不会当天购买当天卖出),当前总收益 s e l l = 0 sell = 0 sell=0
之后从第二天开始遍历到最后一天,遍历过程中:
- b u y = max ( b u y , s e l l − p r i c e s [ i ] ) buy = \max(buy, sell - prices[i]) buy=max(buy,sell−prices[i])
- s e l l = max ( s e l l , b u y + p r i c e s [ i ] − f e e ) sell = \max(sell, buy + prices[i] - fee) sell=max(sell,buy+prices[i]−fee)
最终返回 s e l l sell sell即可。
- 时间复杂度 O ( l e n ( p r i c e s ) ) O(len(prices)) O(len(prices))
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
class Solution {
public:int maxProfit(vector<int>& prices, int fee) {int buy = -prices[0], sell = 0;for (int i = 1; i < prices.size(); i++) {buy = max(buy, sell - prices[i]);sell = max(sell, buy + prices[i] - fee);}return sell;}
};
Python
# from typing import Listclass Solution:def maxProfit(self, prices: List[int], fee: int) -> int:buy, sell = -prices[0], 0for i in range(1, len(prices)):buy = max(buy, sell - prices[i])sell = max(sell, buy + prices[i] - fee)return sell
同步发文于CSDN,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/133609633
这篇关于LeetCode 0714. 买卖股票的最佳时机含手续费的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!