Lintcode149 Best Time to Buy and Sell Stock solution 题解

来源:互联网 发布:mysql truncate函数 编辑:程序博客网 时间:2024/06/07 06:06

【题目描述】

Say you have an array for which theithelement is the price of a given stock on dayi.

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.

假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

【题目链接】

www.lintcode.com/en/problem/best-time-to-buy-and-sell-stock/

【题目解析】

I限制了只能买卖一次。于是要尽可能在最低点买入最高点抛出。这里的一个隐含的限制是抛出的时间必须在买入的时间之后。所以找整个数组的最大最小值之差的方法未必有效,因为很可能最大值出现在最小值之前。但是可以利用类似思路,在扫描数组的同时来更新一个当前最小值minPrice。这样能保证当扫到i时,minPrices必然是i之前的最小值。当扫到i时:

如果prices[i] < minPrice,则更新minPrice = prices[i]。并且该天不应该卖出。

如果prices[i] >= minPrice,则该天可能是最好的卖出时间,计算prices[i] - minPrice,并与当前的单笔最大利润比较更新。

【参考答案】

www.jiuzhang.com/solutions/best-time-to-buy-and-sell-stock/

原创粉丝点击