LeetCode-714:Best Time to Buy and Sell Stock with Transaction Fee (带有抛售费用的股票最大利润) -- medium

Question

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2

Output: 8

Explanation: The maximum profit can be achieved by:

Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Note:

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

问题解析:

给定数组,其中的元素代表当天的股票价格,不限制股票的购售次数,但要求在购买新股之前要售出之前的股票,求股票交易的最大利润。每次股票交易都要支付固定的交易费。

Answer

Solution 1:

DP。

  • 与之前的LeetCode-121:Best Time to Buy and Sell Stock (一次股票交易最大利润)LeetCode-122:Best Time to Buy and Sell Stock II (多次股票交易最大利润)相似,均为股票交易题目,但本题增加了交易费的条件。
  • 分析每天的行为,我们可以知道,主要的行为就是售出和购入。所以我们建立两个动态规划数组:sold和hold,其中sold[i]保存的是第i天出售股票后的最大利润,hold[i]保存的是第i天持有股票的最大利润。
  • sold[i]有两个状态,一个是在i天售出的利润,或者保持前一天也就是sold[i-1]的售出利润,选择其中的最大利润。
  • hold[i]也有两个状态,一个是在i天购入的利润,或者保持前一天也就是hold[i-1]的持有利润,选择其中的最大利润。
  • 写为动态规划式为:
    Soldi=Max(Soldi1,Holdi1+Pricesifee); Holdi=Max(Holdi,Soldi1Pricesi)
class Solution {
    public int maxProfit(int[] prices, int fee) {
        int n = prices.length;
        if (n < 2) return 0;

        int[] sold = new int[n];
        int[] hold = new int[n];
        hold[0] = -prices[0];

        for (int i = 1; i < n; i++){
            sold[i] = Math.max(sold[i-1], hold[i-1] + prices[i] - fee);
            hold[i] = Math.max(hold[i-1], sold[i-1] - prices[i]);
        }

        return sold[n-1];
    }
}
  • 时间复杂度:O(n),空间复杂度:O(n)
Solution 2:

DP优化。

  • 同样,与LeetCode-152:Maximum Product Subarray (乘积最大连续子数组)相同,Solution 1 的解法可以做空间上的优化。因为动态规划公式中每次计算使用的只有上一次的结果,所以,我们将前一次的结果做临时的保存即可实现空间上的优化。
class Solution {
    public int maxProfit(int[] prices, int fee) {
        int n = prices.length;
        if (n < 2) return 0;

        int sold = 0;
        int hold = -prices[0];

        for (int i = 1; i < n; i++){
            int soldpre = sold;
            sold = Math.max(soldpre, hold + prices[i] - fee);
            hold = Math.max(hold, soldpre - prices[i]);
        }

        return sold;
    }
}
  • 时间复杂度:O(n),空间复杂度:O(1)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值