leetcode Best Time to Buy and Sell Stock III

本文介绍了一种计算股票买卖最大收益的算法,通过两次交易机会获取最大利润。首先提出了一种时间复杂度为O(n^2)的直观解法,并对其进行优化,最终实现了时间复杂度更低的有效解决方案。

题目要求之多两次事务得到的最大收益。

较为自然的联想到以时间 i 为分界点,求出 0- - -i 与 i+1- - -end之间的最大效益,分别比较大小以及两者之和的大小即可获得最大利润。


代码(超时)

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        maxNum = 0;
        if(prices.size()==0||prices.size()==1)
            return 0;
        
        for(int i = prices.size()-1; i >= 0; --i)
        {
            int sum1 = getMax(0, i-1, prices);
            int sum2 = getMax(i, prices.size()-1, prices);
            int sum3 = sum1+sum2;
            maxNum = max(sum3, max(sum1, sum2));
            
        }
        
        return maxNum;
    }
    
    
    int getMax(int start, int end, vector<int> &prices)
    {
        if(start==end||start>end||start<0||end<0)
          return 0;
        int maxSold = prices[end];
        int maxNum = 0;
        for(int i = end; i >= 0; --i)
        {
            maxSold = max(prices[i], maxSold);
            maxNum = max(maxNum, maxSold - prices[i]);
            
        }
        
        return maxNum;
        
    }   
    
    
private:
    int maxNum;
};

上述算法时间复杂度为O(n^2)


参考网上资料可以优化代码(Accepted)

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        maxNum = 0;
        int len = prices.size();
        if(len<=1)
            return 0;
        int maxFromHead[len];
        
        int minBought = prices[0];
        int maxPrice = 0;
        
        for(int i = 0; i < prices.size(); ++i)
        {
           minBought = min(minBought, prices[i]);
           maxPrice = max(maxPrice, prices[i]-minBought);
           maxFromHead[i] = maxPrice;
            
        }
        
        
        int maxSold = prices[len-1];
        maxPrice = 0;
        maxNum = maxFromHead[len-1];
        for(int i = len-1; i >= 0; --i)
        {
            maxSold = max(maxSold, prices[i]);
            maxPrice = max(maxPrice, maxSold - prices[i]);
            maxNum = max(maxNum, maxPrice+maxFromHead[i-1]);
        }
        
        return maxNum;
    }
    
    
  
    
private:
    int maxNum;
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值