[LeetCode] 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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.

这道题暴力解法肯定是O(N2), 但有O(1)的解法。
有个思维陷阱是找到最小值然后看最小值之后的最大值,但其实是不对。[3,7,1,2], 第一个波峰波谷的差值已经记录再profix里面了,后面第二个波峰波谷并没有第一个来的更大。

其实这道题是求一个最大的差额,可以用两个变量,一个变量buy来记录应该买入的点,另一个变量profix来记录利差。当循环开始,可以比较当前的值和buy的值留住最小,profix则可以看看当前的值和buy之间的差额和profix之间留下最大。不用担心buy被更小的值更新,因为买点更低会和后面的差值越大,之前的波峰波谷值都已经被profix记录了。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices: return 0
        buy, profit = sys.maxsize, -sys.maxsize-1
        for price in prices:
            buy = min(buy, price)
            profit = max(profit, price - buy)
        return profit

posted on 2020-04-07 07:50  codingEskimo  阅读(106)  评论(0编辑  收藏  举报

导航