Best Time to Buy and Sell Stock III

本文介绍了一种通过动态规划解决股票交易最大收益问题的方法。利用两个动态数组dp_head和dp_tail分别记录从前向后和从后向前的最佳交易时机,最终得出最大可能收益。

题目大意: 有一支股票, 你买入和卖出的机会最多两次,且不能在同一天买进和卖出。让你求最大的收益。

解题思路:动态规划。

用dp_head[i]表示0~i的序列,股票最多交易一次的最大收益

dp_tail[i]表示i~end的序列,股票最多交易一次的最大收益。

然后求max(dp_head[i] + dp_tail[i+1]).


#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <climits>
using namespace std;

class Solution {
public:
	int maxProfit(vector<int> &prices) {
		if(prices.empty() || prices.size() == 1)
		  return 0;
		vector<int> dp_head(prices.size(), 0);
		vector<int> dp_tail(prices.size(), 0);
		int cur_min = INT_MAX;
		int i = 0;
		for(vector<int>::iterator iter = prices.begin(); iter != prices.end(); iter++) {
			cur_min = min(cur_min, *iter);
			if(i == 0) {
				dp_head[i] = 0;
			}
			else {
				dp_head[i] = max(dp_head[i - 1], *iter - cur_min);
			}
			i++;
		}
		i = prices.size() - 1;
		int cur_max = INT_MIN;
		for(vector<int>::reverse_iterator iter = prices.rbegin(); iter != prices.rend(); iter++) {
			cur_max = max(cur_max, *iter);
			if(i == prices.size() - 1) {
				dp_tail[i] = 0;
			} else {
				dp_tail[i] = max(dp_tail[i + 1], cur_max - *iter);
			}
			i--;
		}
		int profit = 0;
		for(int k = 0; k < prices.size(); k++) {
			if(k == 0) {
				profit = max(profit, dp_tail[k]);
			} else if(k == prices.size() - 1) {
				profit = max(profit, dp_head[k]);
			} else {
				profit = max(profit, dp_head[k] + dp_tail[k+1]);
			}
		}
		return profit;
	}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值