Best Time to Buy and Sell Stock III

来源:互联网 发布:java版波斯王子2下载 编辑:程序博客网 时间:2024/05/21 19:38

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

解题思路:动态规划。

用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;}};


0 0