1. 程式人生 > >Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock III

urn 曾經 -s 查找 tip 依據 都是 sign snippet

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切割。前後加起來最大的情況。
另外還看到了一個求最大k次交易的一個通用算法,是依據一篇論文寫出來的,看來學術確實能用到尋常的編程裏來,事實上想想如今的二分查找等算法不都是曾經的論文麽。


int maxProfitIII(vector<int> &prices) 
{
	int len = prices.size();
	if (len == 0) return 0;

	vector<int> history(len, 0);
	vector<int> future(len, 0);

	int low = prices[0];
	for (int i = 1; i < len; i++)
	{
		history[i] = max(history[i-1], prices[i] - low);
		low = min(low, prices[i]);
	}

	int high = prices[len-1];
	for (int i = len-2; i >= 0; i--)
	{
		future[i] = max(future[i+1], high - prices[i]);
		high = max(high, prices[i]);
	}

        int maxProfit = 0; // 網上說第一次的賣和第二次的買能夠在同一次。所以直接都是i相加就能夠了
	for (int i = 0; i < len; i++)
	{
		maxProfit = max(maxProfit, history[i] + future[i]);
	}
		
	return maxProfit;
}

Best Time to Buy and Sell Stock III