Best Time to Buy and Sell Stock

本文介绍了一种算法,用于在给定的股票价格数组中找到最大交易利润。通过维护一个最低价格和最大利润变量,该算法能在O(n)的时间复杂度内完成计算,空间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

这题是一系列最佳买卖股票题目当中的第一题,也是最简单的。看题意可明白,买应在卖之前,利润最大,即在前面找到一个价格的最小值,在后面寻找一个最大值获取最大差价。可以维护一个min_price变量用于保存到第i-1天区间中的价格最低值。维护max_profit用于保存到第i-1天区间中的可能的利润最大值。则当第i天的价格低于min_price时,没有可能在第i天卖出获得最大利润,此时更新min_price,为后续的区间求值做准备。而如果第i 天的价格高于min_price,则在这天卖出获得最大值,max_profit(i)=max(max_profit(i-1),prices(i)-min_prices(i-1))。虽然问题简单其实蕴含着动态规划的思想,而在更新min_price时存在贪心的思路。代码如下:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        max_profit = 0
        min_price = prices[0]
        length = len(prices)
        for i in xrange(1,length):
            if min_price > prices[i]:
                min_price = prices[i]
            else:
                max_profit = max(max_profit,prices[i]-min_price)
        return max_profit

遍历了一遍数组,时间复杂度O(n),空间复杂度O(1).

转载于:https://www.cnblogs.com/sherylwang/p/5388729.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值