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



class Solution {
public:
	int maxProfit(vector<int>& prices) {
		if (prices.size() < 2)
			return 0;
		vector<int>buy, sell;
		int k = 0;
		while (k + 1 < prices.size())
		{
			while (k + 1 < prices.size()&&prices[k] >= prices[k + 1])
				k++;
			int k1 = k;
			while (k + 1 < prices.size() && prices[k] <= prices[k + 1])
				k++;
			int k2 = k;
			if (k2 != k1)
			{
				buy.push_back(k1);
				sell.push_back(k2);
			}
		}
		int maxp = 0;
		if (buy.empty())
			return 0;
		if (buy.size() == 1)
			return prices[sell[0]] -prices[ buy[0]];
		for (int i = 0; i < buy.size() - 1; i++)
		{
			int max1 = 0;
			for (int j = i; j < buy.size() - 1; j++)
			{
				if (prices[sell[j]]>prices[buy[i]] && prices[sell[j]] - prices[buy[i]]>max1)
				{
					max1 = prices[sell[j]] - prices[buy[i]];
					for (int ii = j + 1; ii < buy.size(); ii++)
						for (int jj = ii; jj < buy.size(); jj++)
							if (prices[buy[ii]]<prices[sell[jj]] && max1 + prices[sell[jj]] - prices[buy[ii]]>maxp)
								maxp = max1 + prices[sell[jj]] - prices[buy[ii]];
				}
			}
		}
		return maxp;
	}
};

性能主要瓶颈是几个for循环部分,有很大的优化余地。

accept


你可能感兴趣的:(LeetCode)