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

想不出来,网上搜了一个算法,从头算一遍。然后在从尾算一遍当前最大值,然后从不同的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;
}

转载于:https://www.cnblogs.com/llguanli/p/7352856.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值