首页 > 其他 > 详细

Best Time to Buy and Sell Stock

时间:2015-03-04 11:09:23      阅读:204      评论:0      收藏:0      [点我收藏+]

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

解题思路:第一个思路是循环遍历购买日和卖出日,然后计算最后最大的利润;结果超时了.第二个思路是由数组末端开始遍历购买日,同时记录卖出价值最高对应的下坐标.

#include<iostream>
#include<vector>
using namespace std;
//一般遍历:超时
int maxProfit(vector<int> &prices) {
	int MaxPro = INT_MIN;

	for (int d_buy = 0; d_buy < prices.size();++d_buy){
		for (int d_sell = d_buy + 1; d_sell < prices.size();++d_sell)
		{
			int Profit = prices[d_sell] - prices[d_buy];
			MaxPro = MaxPro < Profit ? Profit : MaxPro;
		}
	}
	return MaxPro;
}
//记录最大卖出价格日:AC
int maxProfit(vector<int> &prices) {
	
	int MaxPro = 0;
	if (prices.size() < 2)
		return 0;
	for (int d_buy = prices.size() - 2, d_sell = prices.size() - 1; d_buy >= 0; --d_buy)
	{
		int Profit = prices[d_sell] - prices[d_buy];
		if (Profit<0)
			d_sell = d_buy;
		else
			MaxPro = MaxPro < Profit ? Profit : MaxPro;
	}
	return MaxPro;
}


 

 

 

Best Time to Buy and Sell Stock

原文:http://blog.csdn.net/li_chihang/article/details/44056155

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!