首页 > 代码库 > 【leetcode】Best Time to Buy and Sell Stock III

【leetcode】Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock III

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

 
设dpBack[i]为从第一天到第i天的最大的收益
设dpAfter[j]为从第j天到最后一天的最大收益
 
如何求最大收益可以考虑采用Best Time to Buy and Sell Stock I的方法
 
注意是最多买两次,也可以只买一次
 
 1 class Solution { 2 public: 3     int maxProfit(vector<int> &prices) { 4         5         int n=prices.size(); 6         if(n==0)return 0; 7   8         vector<int> dpBack(n),dpAfter(n); 9  10         int maxProfit=0;11         dpBack[0]=0;12         int left=prices[0];13        14         for(int i=1;i<n;i++)15         {16             if(prices[i]>left)17             {18                if(maxProfit<prices[i]-left) maxProfit=prices[i]-left;19             }20             else21             {22                 left=prices[i];23             }24            25             dpBack[i]=maxProfit;26         }27        28         maxProfit=0;29         dpAfter[n-1]=0;30         int right=prices[n-1];31        32         for(int j=n-2;j>=0;j--)33         {34             if(prices[j]<right)35             {36                 if(maxProfit<right-prices[j]) maxProfit=right-prices[j];37             }38             else39             {40                 right=prices[j];41             }42  43             dpAfter[j]=maxProfit;44         }45        46         int result=0;47         for(int i=0;i<n-1;i++)48         {49             if(dpBack[i]+dpAfter[i+1]>result) result=dpBack[i]+dpAfter[i+1];50            51             if(result<dpBack[i+1]) result=dpBack[i+1];52         }53        54         return result;55     }56 };

 

【leetcode】Best Time to Buy and Sell Stock III