121. Best Time to Buy and Sell Stock -Easy

Question

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.

假设给你一个数组,其中第i个元素代表第i天的股票价格。如果你仅被允许最多一次交易(买一次以及卖一次股票)。现在要求你设计出一个算法找到使利益最大的交易

Example

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Solution

  • 动态规划解。我们需要维护一个最大利益的值max_profit和最低买入点low_buy,我们每遇到一个更低的买入点,我们都需要更新low_buy,而对于任意一个买入点,接下来每一天卖出得到有可能得到的利益我们都需要更新max_profit。比如[7, 2, 3, 1, 4],当遇到2,low_buy=2,遇到了3,我们得到当前max_profit=1,遇到了1,low_buy=2,遇到了4,max_profit=3,所以最终返回3

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            if len(prices) == 0: return 0
            max_profit = 0
            low_buy = prices[0]
            for index_p, p in enumerate(prices):
                # 如果当前股票价格小于之前的最低价格,则更新最低价格
                if p < low_buy:
                    low_buy = p
                # 更新最大收益
                elif p - low_buy > max_profit:
                    max_profit = p - low_buy
            return max_profit
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值