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).
方法:参考LeetCode discuss中探讨。
- Get the max profit with one transaction to the full array. Keep down the start and end positions.
-
the start and end positions will be included in the result of two transaction. It falls into two categories: A) it is one full transaction, B) they belong to two separate transactions(start belongs to first transaction and end belongs to second transaction).
-
if A)-- get max profit with one transaction to subarray from 0 to start ; get max profit with one transaction to subarray from end to prices.length.
-
if B)-- get the max profit with one transaction within ****start and end** in **reverse order****
-
return the max profit in those cases
代码如下,是自己写的:
class Solution { public: int len; int minIndex,maxIndex; int maxProfit(vector<int> &prices) { len = prices.size(); if(len<2) return 0; set<int> max_profit; find_minAndMaxIndex(0,len-1,prices); int min = minIndex; int max = maxIndex; //max_profit = prices[maxIndex] - prices[minIndex]; //case A find_minAndMaxIndex(0,min-1,prices); max_profit.insert(prices[maxIndex] - prices[minIndex]+prices[max] - prices[min]); find_minAndMaxIndex(max+1,len-1,prices); max_profit.insert(prices[maxIndex] - prices[minIndex]+prices[max] - prices[min]); //case B vector<int> ReversePrices; for(int j=max-1;j>min;j--){ ReversePrices.push_back(prices[j]); } find_minAndMaxIndex(0, ReversePrices.size()-1,ReversePrices); if(ReversePrices.empty()) max_profit.insert(prices[max] - prices[min]); else max_profit.insert(ReversePrices[maxIndex] - prices[min]+prices[max] - ReversePrices[minIndex]); set<int>::iterator iter = max_profit.end(); iter--; return *iter; } private: void find_minAndMaxIndex(int startIndex,int endIndex,vector<int> &prices){ minIndex=startIndex; maxIndex=startIndex; int minIndexNew = minIndex; int maxProfit = 0; if(startIndex<0||startIndex>=len|| endIndex>=len|| endIndex<0 || startIndex>=endIndex) return ; int min_price = prices[startIndex]; int max_price = prices[startIndex]; for(int i=startIndex+1;i<=endIndex;i++){//找到最小价格和最大价格的下标 if(prices[i]<min_price){ minIndexNew = i; min_price = prices[i]; } else if(maxProfit < prices[i]-min_price){ minIndex = minIndexNew; maxIndex = i; maxProfit = prices[i]-min_price; } }//end for } };