LeetCode Best Time to Buy and Sell Stock III

本文介绍了一种算法,用于计算给定股票价格数组中通过最多两次买卖所能获得的最大利润。该算法分为两个阶段,首先计算从左到右每个位置左侧的最大利润,然后从右到左计算每个位置右侧的最大利润。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

思想:

因为能买2次,假设两次交易分别发生在下标i的左右两边。

f[i]表示截止到下标i位置,左边得到的最大利润;g[i]表示截止到下标i位置,右边得到的最大利润。

求f[i]+g[i]的最大值。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
    	int length = prices.size();
    	if(length < 2)
    		return 0;
    	vector<int> left_max(length,0);
    	vector<int> right_max(length,0);
    	//先买入
    	int cur_min = prices[0];
    	for(int i = 1; i < length; i++) {
    		left_max[i] = max(prices[i] - cur_min, left_max[i-1]);
    		cur_min = min(cur_min, prices[i]);
    	}
    	int cur_max = prices[length-1];	
    	//需要逆序,从右向左,先抛售
    	for(int i = length-2; i > 0; i--) {
    		right_max[i] = max(cur_max - prices[i], right_max[i+1]);
    		cur_max = max(cur_max, prices[i]);
		} 
		int sum = 0;
		for(int i = 1; i < length; i++) {
			sum = max(sum, left_max[i] + right_max[i]);
		}
		return sum;
	}
private:
	int max(const int &a, const int &b) {
		return a > b ? a : b;
	}
	int min(const int &a, const int &b) {
		return a < b ? a : b;
	}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值