LeetCode 121. 买卖股票的最佳时机 Best Time to Buy and Sell Stock

Table of Contents

 

一、中文版

二、英文版

三、My answer

四、解题报告


一、中文版

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

 

二、英文版

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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

三、My answer

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if prices:
            buy, res = prices[0], 0
            for price in prices:
                buy = min(buy,price)
                # sell = max(sell,price)
                res = max(price - buy,res)
            return res
        else:
            return 0
"""
IndexError: list index out of range
Line 3 in maxProfit (Solution.py)
Line 33 in _driver (Solution.py)
Line 44 in <module> (Solution.py)
"""

四、解题报告

1、如果不加 if 进行特判,会报注释中错误。

所以:要充分考虑 Corner case,如本题中的空列表情况。

2、算法思想:遍历 prices,其中每一个 price 都有两个功能:1是与记录的买入的最低价格比较,选出更小值 buy,2 是卖出的价格,每一个 price 去跟当时最小的 buy 比较,计算出最大盈利。

下方官方题解,之所以没有特判,是因为 minprice 直接指定了最小值,而不是像我一样取 prices 中的第一个(这样才需要判断数组是否为空,为空则取不到 prices[0])。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        inf = int(1e9)
        minprice = inf
        maxprofit = 0
        for price in prices:
            maxprofit = max(price - minprice, maxprofit)
            minprice = min(price, minprice)
        return maxprofit

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/121-mai-mai-gu-piao-de-zui-jia-shi-ji-by-leetcode-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

本题与122. 买卖股票的最佳时机 II 的区别在于:II是可以进行多次买卖求最大利润,而 I 只是一次买卖。解题报告详情见:

https://blog.csdn.net/u011675334/article/details/104465476

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值