letcode 714. Best Time to Buy and Sell Stock with Transaction Fee

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.


给定一个数组,数组中的第i个元素为一只股票第i天的价格。现在求买卖股票所能得到的最大值。
如果用贪心的思想去解这道题,应注意 贪心选择 与 产生的子问题无关。因此,只能确定应该在何时买入,而无法确定何时卖出(因为没有标准去衡量赚多少钱是最优的)。所以,我们需要制定一个判断标准去衡量应该在何时买入。
如果对于一个单调上升的数列,其最优解必然是 最大值 - 最小值 。但如果指定的区间内不是单调上升的,那么假定存在一个 比区间最小值大的某个值,和 比区间最大值小的某个值 ,能将这个区间分成两部分,并且使这两部分的各自的 最大值 - 最小值 的和 大于 原区间 最大值 - 最小值。
在这里插入图片描述
这样,从左侧开始遍历数组,按照选择买入的判断标准,不断将原有区间细分,最终求得最优解


class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int len=prices.size();
        if(len==0 || len==1)
            return 0;
        int sum=0;
        int peak=0;
        int least=INT_MAX;
        for(auto ele : prices){
            if(peak-ele>fee){
                sum+=(peak-least-fee);
                least=ele;
                peak=0;
            }
            least=min(ele,least);
            if(ele-least>fee){
                peak=max(peak,ele);
            }
        }
        if(peak-least>fee)
            sum+=(peak-least-fee);
        return sum;
    }
};

注意:

  1. 由于是判断何时买入,所以在执行买入前先执行卖出操作
  2. 卖出操作时注意对下个区间最大值和最小值的初始化
  3. 由于判断何时买入,在没有新的买入前不进行卖出,因此在循环结束时,要进行最后一次卖出
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值