[动态规划]714 Best Time to Buy and Sell Stock with Transaction Fee

Posted fish1996

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[动态规划]714 Best Time to Buy and Sell Stock with Transaction Fee相关的知识,希望对你有一定的参考价值。

problem:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/

        维护两个状态,一个是当前持有股票状态,一个是当前不持有股票状态,两者分别计算最大值。

        在第i天,如果当天不持有股票,那么可能是昨天也没有持有股票,也有可能是当天卖出了股票,所以才没有持有股票。我们从这两种状态中取最大值。

        在第i天,如果当前持有股票,那么可能是昨天就已经持有股票,也有可能是当天买了股票。我们从这两种状态中取最大值。

class Solution 
public:
    int maxProfit(vector<int>& prices, int fee) 
        int n = prices.size();
        vector<int> hasStock(n + 1, 0);
        vector<int> noStock(n + 1, 0);
        hasStock[0] = -50000;
        noStock[0] = 0;
        for(int i = 0;i < n;i++)
        
            noStock[i + 1] = max(noStock[i], hasStock[i] + prices[i] - fee);
            hasStock[i + 1] = max(hasStock[i], noStock[i] - prices[i]);
        
        return noStock[n];
    
;

 

以上是关于[动态规划]714 Best Time to Buy and Sell Stock with Transaction Fee的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode] 714. Best Time to Buy and Sell Stock with Transaction Fee

算法: 买卖股票并且有手续费714. Best Time to Buy and Sell Stock with Transaction Fee

算法: 使用交易费买卖股票的最佳时机714. Best Time to Buy and Sell Stock with Transaction Fee

[动态规划] leetcode 309 Best Time to Buy and Sell Stock with Cooldown

动态规划——Best Time to Buy and Sell Stock IV

LeetCode 188. Best Time to Buy and Sell Stock IV (动态规划)