[LeetCode] 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).

分析:

建立两个一维table,left和right。其中left[i]保存的是在第i天之前做一次交易的最大profit;right[i]保存的是在第i天之后做一次交易的最大profit。那么我们最后只需要找到max(left[i] + right[i])即可。那么这两个table怎么建立呢?以left为例(right类似),从做向右推,到第i个位置时候,我们面临两个选择:1)这次交易是在第i天卖出;2)这次交易不是在第i天卖出,也就是在之前的某一天卖出。所以我们有了:left[i] = max(price[i] - min_val, left[i-1]),其中min_val是i天之前的所有价格中的最小值。因此只需遍历一次,我们就可以建立left table,也只需一次(从后向前),我们就可以建立right table。

代码:(O(n))

class Solution {
public:
    int maxProfit(vector<int> &prices) {
		int len = prices.size();
		if (len <= 1) return 0;
		int left[len];
		left[0] = 0;
		int min_val = prices[0];
		for (int i = 1; i < len; i ++) {
			left[i] = std::max(left[i-1], prices[i] - min_val);
			min_val = std::min(prices[i], min_val);
		}
		int right[len];
		right[len - 1] = 0;
		int max_val = prices[len - 1];
		for (int i = len - 2; i >= 0; i --) {
			right[i] = std::max(right[i + 1], max_val - prices[i]);
			max_val = std::max(max_val, prices[i]);
		}
		int result = -1;
		for (int i = 0; i < len; i ++) {
			result = max(result, left[i] + right[i]);
		}
		return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值