当前位置:编程学习 > C/C++ >>

leetcode Best Time to Buy and Sell Stock III

I was influenced by the last question. First, I found all starting points and ending points of ascending status as depicted in the last question. However,  these pairs should be divided into two parts. For every part, we needed to find the most ascending sequence. But, the code was written in a lengthy and wrong way.  Even if it was finished, the complexity is o(n^2)
 
 
A solution from my classmate. We could use profit[0][i] to record the maximum profit from 0 to i and profit[1][i] to record the maximum profit from j to end. So it's a dynamic problem, which could be solved in O(n) time. 
 
 
 
class Solution {  
public:  
    int maxProfit(vector<int> &prices) {  
        // Note: The Solution object is instantiated only once and is reused by each test case.  
        int i,j,res=0,buy,sell;  
        vector<int> profit[2];;     
        if(prices.size()==0)            return 0;  
        else{  
            buy=prices[0];  
            profit[0].push_back(0);  
            for(i=1;i<prices.size();i++){  
                if(prices[i]<buy){  
                    profit[0].push_back(profit[0][i-1]);  
                    buy=prices[i];  
                }  
                else{  
                    if(prices[i]-buy>profit[0][i-1])  
                        profit[0].push_back(prices[i]-buy);  
                    else  
                        profit[0].push_back(profit[0][i-1]);  
                }  
            }  
            sell=prices[prices.size()-1];  
            profit[1].push_back(0);  
            for(i=prices.size()-2;i>=0;i--){  
                if( prices[i]>sell ){  
                    profit[1].push_back( profit[1][profit[1].size()-1] );  
                    sell=prices[i];  
                }     
                else{  
                    if( sell-prices[i]>profit[1][profit[1].size()-1] )  
                        profit[1].push_back(sell-prices[i]);  
                    else  
                        profit[1].push_back(profit[1][profit[1].size()-1]);  
                }  
            }     
  
            for(i=0;i<profit[0].size();i++){  
                if( profit[0][i]+profit[1][profit[0].size()-1-i]>res )  
                    res=profit[0][i]+profit[1][profit[0].size()-1-i];  
            }  
         }  
         return res;  
    }  
};  

 

 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,