leetcode @python 121. Best Time to Buy and Sell Stock

题目链接

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

题目原文

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.

题目大意

给定不同交易日股票的价格,只能做一次交易(只能做一次买入和卖出),返回最大的收益

解题思路

更新当前最低的股票价格,更新每个价格与最低价格的差值,取最大值

代码

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) < 1:
            return 0
        low = prices[0]
        profit = 0
        for i in range(len(prices)):
            if prices[i] < low:
                low = prices[i]
            profit = max(profit, prices[i] - low)
        return profit     
原文地址:https://www.cnblogs.com/slurm/p/5345958.html