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.

此题看清题,最多俩次交易。且俩次交易不能重叠。

个人第一次思路,计算f(0,i)与f(i,n)的最大值。可知O(N^2) 代码超时!但正确 。

int maxProfit(vector<int> &prices) 
{

	if(prices.size() <2 )return 0;
	int max_profit = 0;
	int min_val ;
	for(int k = 0;k < prices.size();k++) 
	{

		min_val = prices[0];
		int profit_1 = 0;

		for(int i = 1;i < k;i++)
		{
			if(min_val > prices[i])
			{
				min_val = prices[i];
			}
			if(profit_1 < prices[i] - min_val)
			{
				profit_1 = prices[i] - min_val;
			}

		}

		min_val = prices[k];
		int profit_2 = 0;

		for(int i = k+1;i < prices.size();i++)
		{
			if(min_val > prices[i])
			{
				min_val = prices[i];
			}
			if(profit_2 < prices[i] - min_val)
			{
				profit_2 = prices[i] - min_val;
			}

		}
		int val = profit_2 + profit_1;
		if(max_profit < val)
		{
			max_profit = val;
		}
	}

	return max_profit;
}
第二次:感觉,需要缓存。参看他人的代码! http://www.cnblogs.com/lihaozy/archive/2012/12/19/2825525.html
利用缓存,分别0--》n 计算最大 利润值。再重n--->0计算最大利润值。

最后利用缓存值,找俩次最大和!O(n)

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

int maxProfit(vector<int> &prices);

int main()
{
	int a[] = {2,1,2,0,1};
	vector<int> prices(a,a+5);
	cout<<maxProfit(prices)<<endl;

	return 0;
}

int maxProfit(vector<int> &prices) 
{

	if(prices.size() <2 )return 0;

	int max_profit = 0;
	int min_val ;
	int max_val;

	vector<int> profit_left(prices.size());
	vector<int> profit_right(prices.size());

	profit_left[0] = 0;
	profit_right[prices.size()-1] = 0;

	min_val = prices[0];
	int max_profit_left = 0;
	for(int i = 1;i < prices.size();i++) 
	{
		if(min_val > prices[i])
		{
			min_val = prices[i];
		}
		if(max_profit_left < prices[i] - min_val)
		{
			max_profit_left = prices[i] - min_val;
		}
		
		profit_left[i] = max_profit_left;
		
	}

	max_val = prices[prices.size()-1];
	int max_profit_right = 0;
	for(int i = prices.size()-2;i >= 0;i--) 
	{    

		if(max_val < prices[i])
		{
			max_val = prices[i];
		}
		if(max_profit_right < max_val -prices[i] )
		{
			max_profit_right = max_val -prices[i];
			 
		}
		
		profit_right[i] = max_profit_right;
		

	}

	for(int i = 0; i < prices.size();i++)
	{
		cout<<profit_left[i] <<" "<< profit_right[i]<<endl; 
		if(max_profit < profit_left[i] + profit_right[i])
		{
			max_profit = profit_left[i] + profit_right[i];
		}
	}

	return max_profit;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值