Leetcode第309、714题 买卖股票的最佳时机C++解法

动态规划

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int n=prices.size();
        if(n<2)  return 0;
        int buy[n],sell[n],froze[n];
        buy[0]=-prices[0],sell[0]=0,froze[0]=0;
        for(int i=1;i<n;++i)
        {
    
    
        buy[i]=max(buy[i-1],froze[i-1]-prices[i]);
        sell[i]=max(sell[i-1],buy[i-1]+prices[i]);
        froze[i]=max(froze[i-1],sell[i-1]);}
        return sell[n-1];
    }
};

优化下空间其实也可以用2*3数组来实现

int newfroze=max(froze,sell);
int newsell=max(sell,buy+prices[i]);
int newbuy=max(buy,froze-prices[i]);
froze=newfroze;
sell=newsell;
buy=newbuy;
class Solution {
    
    
public:
    int maxProfit(vector<int>& prices, int fee) {
    
    
        int n=prices.size();
        if(n<2) return 0;
        int sell[n],buy[n];
        buy[0]=-prices[0]-fee;sell[0]=0;
        for(int i=1;i<n;++i)
        {
    
    
            buy[i]=max(buy[i-1],sell[i-1]-prices[i]-fee);
            sell[i]=max(sell[i-1],buy[i-1]+prices[i]);
        }
        return sell[n-1];
    }
};

714题

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices, int fee) {
    
    
        int n=prices.size();
        if(n<2) return 0;
        int sell[n],buy[n];
        buy[0]=-prices[0]-fee;sell[0]=0;
        for(int i=1;i<n;++i)
        {
    
    
            buy[i]=max(buy[i-1],sell[i-1]-prices[i]-fee);
            sell[i]=max(sell[i-1],buy[i-1]+prices[i]);
        }
        return sell[n-1];
    }
};

实际上可以直接用两个变量就可以满足

buy=max(buy,sell-p-fee);
sell=max(sell,buy+p);

也可以用贪心去做,实际上122题用贪心的时候,我也不知道是怎么写出来贪心的,就是凭感觉。而这一次,却写不出来

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices, int fee) {
    
    
        int n=prices.size();
        if(n<2) return 0;
        int buy=prices[0]+fee,res=0;
        for(int i=1;i<n;++i)
        {
    
    
            if(prices[i]+fee<buy)
                buy=prices[i]+fee;
            else if(prices[i]>buy)
            //这里我一开始直接是else,显然错了
                {
    
    res+=prices[i]-buy;
                buy=prices[i];}
            cout<<"buy  "<<buy<<"res    "<<res;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/meixingshi/article/details/113849128