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

题目链接

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

题目描述

给定一个整数数组 p r i c e s prices prices,其中 p r i c e s [ i ] prices[i] prices[i] 表示第 i i i 天的股票价格 ;整数 f e e fee 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 ≤ p r i c e s . l e n g t h ≤ 5 ∗ 1 0 4 1 \leq prices.length \leq 5 * 10^4 1prices.length5104
  • 1 ≤ p r i c e s [ i ] < 5 ∗ 1 0 4 1 \leq prices[i] < 5 * 10^4 1prices[i]<5104
  • 0 ≤ f e e < 5 ∗ 1 0 4 0 \leq fee < 5 * 10^4 0fee<5104

本题类似于 Leetcode.714 买卖股票的最佳时机含手续费
,就是交易完成的时候多了一份手续费。

参考题解:Leetcode.714 买卖股票的最佳时机含手续费 题解

解法一:记忆化搜索

时间复杂度: O ( n ) O(n) O(n)

C++代码:

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n = prices.size();
        int f[n][2];
        memset(f,-1,sizeof f);

        function<int(int,int)> dfs = [&](int i,int hold) ->int{
            if(i < 0){
                return hold ? -1e9 : 0;
            }

            if(f[i][hold] != -1) return f[i][hold];

            //持有股票
            if(hold) f[i][1] = max(dfs(i - 1,1),dfs(i - 1,0) - prices[i]);
            //未持有股票
            else f[i][0] = max(dfs(i - 1,0),dfs(i - 1,1) + prices[i] - fee);

            return f[i][hold];
        };

        return dfs(n - 1,0);
    }
};

解法二:动态规划

时间复杂度: O ( n ) O(n) O(n)

C++代码:

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n = prices.size();
        int f[n][2];
        memset(f,0x80,sizeof f);

        f[0][0] = 0 , f[0][1] = -prices[0];
        for(int i = 1;i < n;i++){
            f[i][0] = max(f[i - 1][0],f[i - 1][1] + prices[i] - fee);
            f[i][1] = max(f[i - 1][1],f[i - 1][0] - prices[i]);
        }

        return f[n - 1][0];
    }
};

解法三:动态规划 + 优化空间

时间复杂度: O ( n ) O(n) O(n)

C++代码:

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int f0 = 0 , f1 = -1e9;
        for(auto p:prices){
            int new_f0 = max(f0,f1 + p - fee);
            f1 = max(f1 , f0 - p);
            f0 = new_f0;
        }

        return f0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值