Leetcode--Best Time to Buy and Sell Stock III

Problem Description:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

分析:

按照题意,要求根据每天的股票价格,交易两次得到最大的利润。直接的想法就是利用分治法,从前往后循环依次将数组分为前后两个股票价格序列,分别得到最大的利润,将两者相加得到两次交易的最大利润,时间复杂度O(n^2),提交果然超时了。

代码如下:

class Solution {
public:

    int profit(vector<int> &vec,int beg,int last)
    {
        int res=0;
        if(beg==last)
            return res;
        int min=vec[beg];
        for(int i=beg+1;i<=last;++i)
        {
            if(vec[i]>min)
            {
                int temp=vec[i]-min;
                if(temp>res)
                    res=temp;
            }
            else
                min=vec[i];
        }
        return res;
    }

    int maxProfit(vector<int> &prices) {
        int res=0;
        int n=prices.size();
        if(n<=1)
            return res;

        for(int i=1;i<n-1;i++)
        {
            int res1=profit(prices,0,i);
            int res2=profit(prices,i+1,n-1);
            if((res1+res2)>res)
                res=res1+res2;
        }

        return res;
    }
};

看了discus以后发现其实可以在O(n)时间内将前后两部分的最大利润求出来,具体实现就是用两个数组分别存储从前往后和从后往前两次遍历时每天的最大利润,最后得到两次交易能够获得的最大利润。

具体代码如下:

class Solution {
public:

    int maxProfit(vector<int> &prices) {
        int res=0;
        int n=prices.size();
        if(n<=1)
            return res;
        vector<int> front(n,0);
        vector<int> back(n,0);
        int minp=prices[0];
        int maxp=prices[n-1];
        for(int i=1;i<n;i++)
        {
            if(prices[i]>minp)
                front[i]=prices[i]-minp;
            else
                minp=prices[i];
        }
        for(int i=n-2;i>=0;i--)
        {
            if(prices[i]>maxp)
                maxp=prices[i];
                
            back[i]=max(maxp-prices[i],back[i+1]);
            if(front[i]+back[i]>res)
                res=front[i]+back[i];
                
        }

        return res;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值