【LeetCode】121. 买入和卖出股票的最佳时间

问题描述

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.

假设你有一个数组,其中的第i个元素是某只股票在第一天的价格。
如你最多只获准完成一项交易(即,买一股,卖一股),设计一个算法来寻找最大的利润。
注意,你不能在买股票之前卖掉它。

输入: [7,1,5,3,6,4]
输出: 5
说明: 在第二天(price = 1)买入,在第五天(price = 6)卖出,利润为5.
      不能在第一天(price = 7)卖出,在第二天(price = 1)买入,因为买入必须要在卖出前完成。

输入: [7,6,4,3,1]
输出: 0
说明: 在这个例子中,不进行任何交易,也就是说,最大利润为0.

Python 实现

这里需要注意的是,题目要求买入必须在卖出前实现,因此需要保证小值在前,大值在后,因此不能简单地找出最大值和最小值来解答这个问题。在遍历每个价格时,我们每次只进行一次更新操作,要么更新最小价格,要么在新的最小价格的基础上,再通过当前的价格来更新最大利润。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        
        length = len(prices)
        if length < 2:
            return 0
        
        lowest_price = float('inf')
        profit = 0
        
        for price in prices:
            # Update if finding a lower price.
            if price < lowest_price:
                lowest_price = price
            # Update the profit if the current price is available to higher profit with the newest lowest_price.
            elif price - lowest_price > profit:
                profit = price - lowest_price
        return profit

链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值