leetcode Best Time to Buy and Sell Stock III

来源:互联网 发布:centos syslog服务器 编辑:程序博客网 时间:2024/06/17 12:23

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).


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);elseprofit[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]);elseprofit[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;    }};


原创粉丝点击