美文网首页
每天(?)一道LeetCode(14) Best Time to

每天(?)一道LeetCode(14) Best Time to

作者: 失业生1981 | 来源:发表于2019-01-28 21:35 被阅读0次

Array

121. Best Time to Buy and Sell Stock

Say you have an array for which the i^{th} 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.

即在最便宜的时候买入,在最贵的时候卖出,挣的差额,但是要先买入才能卖出

Solutions
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max_profit, min_price = 0, float("inf")
        for price in prices:
            min_price = min(min_price, price)
            max_profit = max(max_profit, price - min_price)
        return max_profit

相关文章

网友评论

      本文标题:每天(?)一道LeetCode(14) Best Time to

      本文链接:https://www.haomeiwen.com/subject/okvzjqtx.html