Leetcode 714:买卖股票的最佳时机含手续费

题目描述

给定一个整数数组 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.
注意:

0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

超时dp。

class Solution {
public:
    
    int maxProfit(vector<int>& prices, int fee) {
        int len=prices.size();
        vector<int> dp(len);
        for(int i=1;i<len;++i){
            int cur = dp[i-1],tmp = prices[i];
            for(int j=i-1;j>=0;--j){
                if(tmp<=prices[j]+fee) continue;
                int t = (j-1>=0)?dp[j-1]:0;
                cur = max(cur,tmp-prices[j]-fee+t);
            }
            dp[i] = cur;
        }
        return dp[len-1];
    }
    
};

Ac dp

class Solution {
public:
       
    int maxProfit(vector<int>& prices, int fee) {
        int len=prices.size();
        vector<int> buy(len),sale(len);
        buy[0]=-prices[0];
        for(int i=1;i<len;++i){
            buy[i]=max(buy[i-1],sale[i-1]-prices[i]);
            sale[i]=max(sale[i-1],buy[i-1]+prices[i]-fee);
        }
        return sale[len-1];
    }
};
发布了584 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_35338624/article/details/104072471
今日推荐