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.

解析:在给定的数组中,求最大值和最小值的差值即为所得。要求是这里的最大值在最小值的后面出现。一般而言,我们处理问题总是习惯从前向后处理,这个题目中从后向前处理显的更符合逻辑。在现实中,我们买了股票总是处于观望状态,总是期望价钱越来越高,即使出现短期的回落,我们也总是希望并相信未来会上扬。从另一个角度来说,我们从当前去看未来总是感觉扑朔迷离,但是当前看过去却看得分外清晰。

所以我们从交易的最后一天作出售开始(再不卖交易截止了,废了),我们开始向前去找,找到比出售这天价钱低的,我们求一下此时的利润,要是比当前的最大利润要高,我们更改最大值,并继续向前找,因为我们总是希望并相信还有更低的买进价格,直到走到开盘那天(下标0),若这其中遇到比出售的价格高的情况,我们就将当前遇到的这个高的价格作为出售价格,继续以上的操作,最后获得最大利润。

class Solution {
public:
    int maxProfit(vector<int> &stock) {
    int sell = stock.size() - 1;
	int max_profit = 0;
	for(; sell >= 0; ){
		int buy = sell - 1;
		int cur_profit = 0;
		int cur_pay = 0;
		while (buy >= 0 && stock[buy] < stock[sell])
		{
			cur_profit = stock[sell] - stock[buy--];
			if(cur_profit > max_profit)
				max_profit = cur_profit;
		}	
		sell = buy;
	}
	return max_profit;
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值