LeetCode动态规划+贪心 买卖股票的最佳时机含手续费

You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

思路
这道题假如没有卖出时的手续费这个条件,那么其实是常见的动态规划+贪心问题,那么这道题多了一个手续费该如何处理呢?
其实,只需要把手续费当作是买入股票时的成本,在表示买入价格的dp数组中,把手续费也加进数组元素中就好啦。

状态转移方程
dp[i] = min(dp[i-1], prices[i] + fee)

边界条件
dp[0] = prices[0] + fee

代码

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int len = prices.size();
        int dp[50005] = {0};
        dp[0] = prices[0] + fee;
        int sum = 0;

        prices.push_back(0);
        for(int i = 1; i < len; i++)
        {
            dp[i] = min(dp[i-1], prices[i] + fee);
            if(prices[i] - dp[i-1] > 0 && prices[i] > prices[i+1])
            {
                sum += prices[i] - dp[i-1];
                dp[i] = prices[i];
            }
        }

        return sum;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值