100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 【LeetCode】121. 买入和卖出股票的最佳时间

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

时间:2024-07-23 11:58:59

相关推荐

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

问题描述

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 (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 0lowest_price = float('inf')profit = 0for 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_pricereturn profit

链接:/problems/best-time-to-buy-and-sell-stock/

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。