121买卖股票的最佳时机

题目:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。注意你不能在买入股票前卖出股票。
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock

法一:自己的代码

思路:不断更新最小值,求当前值与最小值的差,

# 执行用时 :64 ms, 在所有 Python3 提交中击败了93.54% 的用户
# 内存消耗 :14.5 MB, 在所有 Python3 提交中击败了64.84%的用户
from typing import List
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        m = float('inf')
        ans = 0
        for i in prices:
            # m记录之前的最小值
            if i < m:
                m = i
            # 如果不是最小值,则与最小值作差求最大值
            else:
                ans = max(i-m, ans)
        return ans
if __name__ == '__main__':
    duixiang = Solution()
    a = duixiang.maxProfit([7,1,5,3,6,4])
    print(a)
View Code

ttt

posted on 2020-02-15 15:53  吃我一枪  阅读(97)  评论(0编辑  收藏  举报

导航