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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值