Fork me on GitHub

121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

题目

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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

解析

//Best Time to Buy and Sell Stock
class Solution_121 {

		//分析一下价格曲线的不同走势对应的不同操作:
		//上升沿:此时都是收益的,我们需要判断现在的价格减去之前保留的最低的价格是否大于之前计算的最大收益即可。
		//下降沿:此时收益在降低,我们只需要判断新的价格是不是比之前保留的最低价格还要低即可。

	//1. 从后往前算, 因为卖肯定要比买之后,从后往前找到最大值,和当前值做差,差值的最大值就是获取的最大利润 
	//2. 找到第i天之前的最小值,然后prices[i] - min与最大收益maxprofit比较
	// 从前或者从后逆序都可以

public:
	int maxProfit_1(vector<int>& prices) {   //Time Limit Exceeded

		int ret = 0;

		for (int i = 0; i < prices.size()-1;i++)
		{
			for (int j = i+1; j < prices.size();j++)
			{
				if (prices[j]-prices[i]>=0)
				{
					ret = max(ret, prices[j] - prices[i]);
				}
			}
		}
		return ret;
	}

	int maxProfit(vector<int>& prices) {

		if (prices.size()<=1)
		{
			return 0;
		}
		int max_profit = 0;
		int cur_profit = 0;
		int cur_min = prices[0];
		for (int i = 1; i < prices.size();i++)
		{
			if (prices[i]<cur_min)
			{
				cur_min = prices[i]; //更新当前最小值
			}
			cur_profit = prices[i] - cur_min;
			if (cur_profit>max_profit)
			{
				max_profit = cur_profit;
			}
		}
		return max_profit;
	}
};

题目来源

posted @ 2018-01-04 11:44  ranjiewen  阅读(293)  评论(0编辑  收藏  举报