标签:
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).
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 else 21 { 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 else 39 { 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
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4194631.html