码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock III

时间:2015-03-04 17:04:16      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:要求两次交易的最大利润.将整个序列分两个区别来讨论,分别计算两个区间的最大值.

若用两个循环来遍历则重复的计算过多.因此利用动态规划的思想首先记录买入日为i的最大利润p[i];

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int maxProfit(vector<int> &prices) {
	int N  = prices.size();
	if (N <=1)
		return 0;
	vector<int>p(N, 0);
	for (int idx_buy = N - 2,idx_sell = N-1; idx_buy >= 0; --idx_buy){
		int Profit = prices[idx_sell] - prices[idx_buy];
		idx_sell = Profit < 0 ? idx_buy : idx_sell;
		p[idx_buy] = Profit>p[idx_buy + 1] ? Profit : p[idx_buy + 1];
	}
	int MaxProfit = 0;
	for (int idx_buy = 0, idx_sell = 1; idx_sell < N;++idx_sell)
	{
		int Profit = prices[idx_sell] - prices[idx_buy];
		idx_buy = Profit < 0 ? idx_sell : idx_buy;
		MaxProfit = Profit + p[idx_sell]>MaxProfit ? Profit + p[idx_sell] : MaxProfit;
	}
	return MaxProfit;

}


 

 

 

Best Time to Buy and Sell Stock III

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/44060959

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!