#123 Best Time to Buy and Sell Stock III
阿新 • • 發佈:2017-11-03
ret 交易 define find one 之間 sel tor arp
/* 找一次操作能獲取最大利潤的一次交易(即題目121)的idxBuy和idxSell,這次交易稱為首次交易 然後分5中情況: 情況1:最優解就只有“首次交易” 情況2:“首次交易”加上左邊的交易得到最優解 情況3:“首次交易”加上右邊的交易得到最優解 情況4:“首次交易”不做,兩邊的交易得到最優解 情況5:“首次交易”不做,idxBuy和idxSell中間找虧損最大的交易idxBuy2,idxSell2,然後idxBuy買,idxBuy2賣,idxSell2買,idxSell賣就是最優解 */ class Solution { public: #define MAX(a,b) ((a)>(b)?(a):(b)) int maxProfit(vector<int>& prices) { if(prices.size() < 2)return 0; //處理首次交易 int idxBuy = 0 ,idxSell = 0; int profitOrigin = this->maxProfitOfOne(prices, 0, prices.size()-1,&idxBuy,&idxSell); int maxProfit = profitOrigin;//默認 //算出左側交易利潤 int profitLeft = this->maxProfitOfOne(prices, 0, idxBuy-1); //算出右側交易利潤 int profitRight = this->maxProfitOfOne(prices, idxSell+1, prices.size()-1); //算出情況1,2,3,4的最大利潤 maxProfit = MAX(profitLeft + profitOrigin, profitRight + profitOrigin); maxProfit = MAX(maxProfit,profitLeft + profitRight); //算出idxBuy,idxSell之間的最大虧損,反過來操作就是更大的盈利 vector<int> pricesRe = prices; reverse(pricesRe.begin(),pricesRe.end()); int maxProfitEx = this->maxProfitOfOne(pricesRe, pricesRe.size() -1- idxSell, pricesRe.size() -1- idxBuy); return MAX(maxProfitEx+profitOrigin,maxProfit); } int maxProfitOfOne(vector<int>& prices, int left, int right,int *pMin=NULL,int *pMax=NULL) { if (left >= right) return 0; int minLop = left, maxLop = left; int maxProfit = 0; int idx = minLop + 1; while (idx < right + 1) { if (prices[idx] > prices[maxLop]) {//find larger maxLop = idx; int profit = prices[maxLop] - prices[minLop]; if (profit > maxProfit) { maxProfit = profit; if(pMin)*pMin = minLop; if(pMax)*pMax = maxLop; } } else if (prices[idx] < prices[minLop]) {//find smaller minLop = idx; maxLop = idx; } idx++; } return maxProfit; } };
#123 Best Time to Buy and Sell Stock III